Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nunit not calling setup once per text fixture

I'm new to Nunit and am trying to run 2 Test Fixtures, A & B. Within each Fixture I have a unique Setup method for each. However, when I click "Run All" in the "Test Explorer" in Visual Studio, the test setup for Fixture A is called (it was executed first) and Setup for Fixture B is ignored. I also get the same behavior when running all tests via command line. Below is my code:

Fixture A

[TestFixture]
public class A
{      
        [SetUp]
        public void SetupTest()
        {
            // ...Setup for Fixture A
        }                

        [Test, Order(1)]
        public void TestForFixtureA()
        {
            // ...perform test
        }
}

Fixture B

[TestFixture]
public class B
{      
        [SetUp]
        public void SetupTest()
        {
            // ...Setup for Fixture B
        }                

        [Test]
        public void TestForFixtureB()
        {
            // ...perform test
        }
}

What is the correct way to get Setup methods to execute per Fixture?

like image 407
usr4896260 Avatar asked Jan 03 '23 23:01

usr4896260


2 Answers

You are using the incorrect attribute for setup at the test fixture level. The attribute you should be using is [SetUpFixture]. Information about this can be found in the nunit documentation

Here is a list of all the setup attributes and their usages taken from the documentation:

  • SetUpAttribute is now used exclusively for per-test setup.

  • TearDownAttribute is now used exclusively for per-test teardown.

  • OneTimeSetUpAttribute is used for one-time setup per test-run. If you run n tests, this event will only occur once.

  • OneTimeTearDownAttribute is used for one-time teardown per test-run. If you run n tests, this event will only occur once

  • SetUpFixtureAttribute continues to be used as at before, but with changed method attributes.

This doesn't seem to explain the bizzare behaviour you are seeing, as setup should be ran per-test, but using the correct attributes couldn't hurt.

like image 137
David Watts Avatar answered Jan 05 '23 16:01

David Watts


If you intend your setup to be run once per fixture, use [OneTimeSetUp]. But if you intend it to run once per test within the fixture, then [SetUp] is correct. We can't tell what you intend from the code.

Whichever one you use, the setups should all run. The only situation in which [OneTimeSetUp] will run but [SetUp] will not is when no individual tests are found within the fixture. Are all the tests being recognized?

I suggest you verify very clearly that the setup is not being run. The easiest way is to temporarily create some output from the setup method.

like image 43
Charlie Avatar answered Jan 05 '23 18:01

Charlie