C# AssemblyInitialize not running - c#

I'm trying to do unit testing on my C# ASP.NET project but need to run some initialization code for all tests:
[TestClass()]
public class Init
{
[AssemblyInitialize]
public static void initialize()
{
ContextProvider.setContext(new TestContext());
}
}
That's all I need to run before my tests, but it is not running. I tried to debug all my tests and put a breakpoint in that line but it is not hit. If I comment out the [AssemblyInitialize] and run one particular test that does not require this initialization, it runs successfully. However, with this line in, no tests run (and no breakpoints at all are hit)
What am I missing here?

Phil1970's helpful comment assisted in resolving the issue.
The problem with the initialize method is that it must receive TestContext (Microsoft.VisualStudio.TestTools.UnitTesting.TestContext). I couldn't find any guide/Microsoft documentation that explicitly states this, but the examples in this msdn page do have TestContext as input for the method.
After I added it, the tests ran successfully. On a side note, I had created a class to mock some data I needed and called it TestContext, which turned out to be a very poor name selection and made it more difficult to understand my mistake. I renamed it to APITestContext, here's my fixed initialization class.
[TestClass()]
public class Init
{
[AssemblyInitialize()]
public static void initialize(TestContext testContext)
{
ContextProvider.setContext(new APITestContext());
}
}

Here is (I think) the full list of things to check:
You should be using Microsoft.VisualStudio.TestTools.UnitTesting;
The class must be public
The class CANNOT be static or abstract
The class must be decorated with [TestClass]
The method must be public
The method MUST be static
The method must be decorated with [AssemblyInitialize]
The method must have the signature: void InitName(TestContext tc)

Don't know if it can be related but in the documentation it says
This attribute should not be used on ASP.NET unit tests, that is, any test with [HostType("ASP.NET")] attribute. Because of the stateless nature of IIS and ASP.NET, a method decorated with this attribute might be called more than once per test run.
Are you using that HostType?

Related

Specflow beforeScenario in base class called multiple times, once for each feature in the suite

I have a test suite that utilizes a test reporting framework that I need to run through a base class, everything works fine but the [BeforeScenario] is being called 10 times for every scenario I run, 1 time for each feature in my suite, strangely the teardown only runs once.
Here is what my base class looks like:
[Binding]
public class BaseStep : AllureReport
{
public DriverSupport _support;
public BaseStep(DriverSupport support)
{
_support = support;
}
[BeforeScenario]
public void Setup(FeatureContext context)
{
_support.startDriver();
AllureLifecycle.Instance.RunStep(() =>
{
TestContext.Progress.WriteLine(
$"Test \"{TestExecutionContext.CurrentContext.CurrentTest.FullName}\" is starting...");
});
}
[AfterScenario, Order(0)]
private void TearDown()
{
AllureLifecycle.Instance.RunStep(() =>
{
TestContext.Progress.WriteLine(
$"Test {TestExecutionContext.CurrentContext.CurrentTest.FullName}\" is stopping...");
});
}
And this is what my feature step file looks like (there are 10 of these)
[Binding]
public class TestSteps1:BaseStep
{
public TestSteps1(DriverSupport support) : base(suppprt)
{
}
[Given(#"user goes to (.*)")]
public void GivenUserGoesTo(string p0)
{
_support.driver.GoToUrl(p0)
}
When I run just ONE scenario in a feature by themselves, it will print start the driver and print "test xxx is starting..." 10 times, once for each feature I have, I just want it to run once.
I have thought of moving beforescenario to the step classes themselves, but many of my features use steps from multiple step files, so I think that would be an issue. Is there any way to make it so it only runs BeforeScenario one time per scenario?
SpecFlow will execute the BeforeScenario method for each type it finds in your test project. It looks like there are 10 types that define or inherit this method:
The BaseStep class
Each sub class of BaseStep
When I want a BeforeScenario to run only once per test run I will put it into its own "hooks" class.
Since both the before and after hooks should only execute once, just put both of them in something like SpecFlowHooks.cs.
The Selenium web driver object should be registered with the SpecFlow dependency injection framework, and passed directly to each step class as a constructor argument. Given the code you posted, I'm not sure a common base class for your step definitions is beneficial.
See my answer for How to properly manage and access webdriver instances to avoid problems with parallel execution of tests? for more information about properly registering a Selenium web driver object with SpecFlow.

What is the order that every builds when running Microsoft Unit Test Framework?

Here's the scoop:
I have a simple test class:
[TestClass]
public class TestClass
{
[TestMethod]
[DataSource("System.Data.SqlClient", DATA_CONN, "myData", DataAccessMethod.Sequential)]
public void Test(){}
[AssemblyInitialize]
public void AssemblyInit(TestContext context)
{
RecreateView("myData"); //why I'm doing this is irrelevant to the question
}
}
When I run this in a scratch project, my AssemblyInit() method runs first, creates the table, and the test is happy. When I run it in a much bigger project with lots of tests, the test method gets built first with the [DataSource] attribute, and then the AssemblyInit() method gets called after.
In short:
Small project - Good
Assembly init recreates view
Test reads view
Large Project - Bad
Test reads view
Assembly init recreates view
I only have one [AssemblyInitialize] method in each project. It also only seems to ever happen locally. Is there a way to guarantee the [AssemblyInitialize] method runs before the tests try to read their data?

writing a test using moq unit testing framework

I'm a bit confused with writing unit tests in C#. I've written the following class for learning Moq. I've noticed the [SetUp] is actually a reference from NUnit. How can I write a test class that only uses one framework or another or whether that's possible? If I want to use Moq what attributes am I missing to successfully run this test? I know there's [TestFixture], [TestMethod] etc.. but which one do I use for Moq!
Thanks,
James
public class CatalogCommandTests
{
private Mock<IReferenceData> _mockReferenceData;
[SetUp]
public void TestInitialize()
{
_mockReferenceData = new Mock<IReferenceData>();
}
public void TestMyGetMethodReturnsListOfStrings()
{
var contractsList = new List<Contract>();
_mockReferenceData.Setup(x => x.MyGetMethod()).Returns(contractsList);
}
}
Your mock looks good. To get the mock of IReferenceData you have to call _mockReferenceData.Object.
A method decorated with the SetUp Attribute will be executed before each test method is called.
(See: Setup).
If you want that TestMyGetMethodReturnsListOfStrings gets called you have to decorate the method with the Test attribute
(See: Test).

Multiple [SetupTest] for different configs

Is it possible to have multiple [SetupTest]'s in a fixture?
I am using Selenium and nUnit and would like to be able to specify the Browser on which the user wants to test.
I have a simple user GUI for selecting tests to run but, I am aware that in the future we want to hook this up to cruise control to run the tests automatically. Ideally I want tests that can be run on both our GUI and the NUnit GUI.
Is it possible to have multiple [SetupTest]'s in a fixture? No.
It is possible to define all your tests in a base class, have multiple fixtures inherit the tests, and then select an environment dependent fixture type at runtime.
Here’s the stock example that I have for [TestFixtureSetup]. The same principle works for all the setup attributes. Notice that I’m only putting [TestFixture] on the child classes. Since the base “TestClass” doesn’t have complete setup code, you don’t want to run the tests directly.
public class TestClass
{
public virtual void TestFixtureSetUp()
{
// environment independent code...
}
[Test]
public void Test1() { Console.WriteLine("Test1 pass."); }
// More Environment independent tests...
}
[TestFixture]
public class BrowserFixture : TestClass
{
[TestFixtureSetUp]
public override void TestFixtureSetUp()
{
base.TestFixtureSetUp();
// environment dependent code...
}
}
[TestFixture]
public class GUIFixture : TestClass
{
[TestFixtureSetUp]
public override void TestFixtureSetUp()
{
base.TestFixtureSetUp();
// environment dependent code...
}
}
I suspect you can use the parameterized tests introduced in NUnit 2.5 to do what you want, but I'm not totally clear what you want to do here. However, you could define the fixture and have it take a Browser variable in its constructor, then use parameterized TestFixture attributes like
TextFixture["Firefox"]
TestFixture["Chrome"]
public class ParameterizedTestFixture {
//Constructor
public ParameterizedTestFixture( string Browser) {
//set fixture variables relating to browser treatment
}
//rest of class
}
See NUnit Documentation for more info.
The Setup attribute identifies a method that is run before each test. It only makes sense to have one Setup per test fixture - think of it as a 'reset' or 'preparation' before each test is run.

Multiple Moles redirection not working from ClassInitialize

I have multiple test methods that depend on the same Mole redirection, and in order to prevent duplication, I've placed the redirection code in my ClassInit Method:
[ClassInitialize]
public static void ClassInit(TestContext context)
{
MBase.AllInstances.BaseMethod = b => "Mole";
}
However, when the test methods are run together the redirection only happens once. Why doesn't the redirection occur for each test method?
Turns out that Moles doesn't support the ClassInitialize method.
For more information on this issue see:
http://social.msdn.microsoft.com/Forums/en-US/pex/thread/c4e432e5-e657-454a-b90f-cfd37803c961?prof=required

Categories

Resources