Search code examples
nunit

OneTimeSetUp runs multiple times in NUnit


The NUnit docs describe how to use SetUpFixture so a chunk of code will execute only once. I'm failing to get this working.

I have read Is it possible to have a [OneTimeSetup] for ALL tests? and https://docs.nunit.org/articles/nunit/writing-tests/attributes/setupfixture.html

I have the following structure for my tests

The actual tests (note the inheritence)

namespace net.UiTests 
{    
    [TestFixture]
    [NonParallelizable]
    internal class SanityTests : TestBase
    {    
        [SetUp]
        public void Initialize()
        {
            //do stuff
        }

        [TearDown]
        public void TestCleanUp()
        {
            //do stuff
        }

        [Test]    
        public void SomeTest()
        {
            //do stuff
        }
    }
}

And the base class, which is where the SetUpFixture lives

namespace net.UiTests
{
    [NonParallelizable]
    [SetUpFixture]
    internal class TestBase
    {
        [OneTimeSetUp]
        public static void AssemblyInit()
        {
            //do stuff
        }

        [OneTimeTearDown]
        public static void AssemblyCleanup()
        {
            //do stuff
        }
    }
}

I am unsure why the AssemblyInit() method executes multiple times. The stack trace gives me no clues other than [External Code]


Solution

  • You have made your base class a SetUpFixture, which is causing the problem.

    The SetUpFixture runs once before and once after all the fixtures in your UiTests namespace.

    But due to inheritance, each TestFixture now "contains" a OneTimeSetUp and a OneTimeTearDown method. Those methods, when found in a TestFixture, are supposed to run once per fixture class and that's what they do.

    To solve the problem, you have to stop using the SetUpFixture as a base class.