Home > Net >  NUnit Test order run test in base class first
NUnit Test order run test in base class first

Time:10-04

Hi I am trying to run tests where each test fixture has a different scenario but each have a common case which I have created a base class/test fixture and said common test needs to run first in my testing order in each test fixture because I am testing api endpoints where the first test (in the base class) needs to send a simple GET request to ensure the endpoint is available and the rest of the tests in each TestFixture tests different requests which is not in commonality with the other test fixtures.

I have managed to order the tests and test fixtures in the order they need to run in, but the test residing in the base class runs last in each fixture even though I specified the order for the base test as 1. Is there anyway to get it so that the Common test runs first, I already know that NUnit runs tests in alphabetical order but that doesn't occur when a test is in a base class.

My code structure looks similar to this:

[TestFixture, Order(1)]
public abstract class BaseClass 
{
    [Test, Order(1)]
    public async Task CommonTest()
    {
         //Perform tests
    }
}

[TestFixture, Order(1)]
public class ClassA : BaseClass
{
    [Test, Order(1)]
    public async Task Test1()
    {
        //Perform Tests
    }

    [Test, Order(2)]
    public async Task Test2()
    {
        //Perform Tests
    }
}

[TestFixture, Order(2)]
public class ClassB : BaseClass
{
    [Test, Order(1)]
    public async Task Test3()
    {
        //Perform Tests
    }

    [Test, Order(2)]
    public async Task Test4()
    {
        //Perform Tests
    }
}

When the tests execute the order is as follows:

ClassA: Test1,
        Test2,
        CommonTest

ClassB: Test3,
        Test4,
        CommonTest

But I require the tests to run in this order

ClassA: CommonTest
        Test1
        Test2

ClassB: CommonTest
        Test3
        Test4        

CodePudding user response:

Such tight ordering of tests under NUnit is a bit of a violation of its design intent, which is to support independent unit tests. That said, you aren't the first person to want to do it. :-)

OrderAttribute orders tests within a TestFixture. An abstract base class is not actually a (runtime) TestFixture, even though you have used the TestFixtureAttribute on it. Rather, the abstract base it contributes code to the actual runtime fixtures fixtures, which are the non-abstract derived classes.

I haven't tried this, but I think you would get the result you want if you reserved some ordering values for use in the abstract base and used values greater than that number in the derived classes.

  • Related