Search code examples
c#unit-testingnunitmstestxunit

MSTest setup/teardown methods that run before and after ALL tests


Relatively new to MSTest v2 in Visual Studio 2019. The TestInitialize attribute indicates the method should run before each and every test. Similarly, TestCleanup indicates the method should run after each and every test.

[TestInitialize()]
public void Setup()
{
    // This method will be called before each MSTest test method
}

[TestCleanup()]
public void Teardown()
{
    // This method will be called after each MSTest test method has completed
}

If your test class has N methods, the above methods will run N times.

Is there a way to signal setup and teardown-like methods that run once only? In other words, for each complete run through all N tests, each method will run once only.

Are there similar mechanisms for NUnit3 and xUnit v2.4.0?


Solution

  • After some hunting, I stumbled on this website with a MSTest "Cheat Sheet" which has examples of what I was looking for (in MSTest):

    [ClassInitialize]
    public static void TestFixtureSetup(TestContext context)
    {
        // Called once before any MSTest test method has started (optional)
    }
    
    [ClassCleanup]
    public static void TestFixtureTearDown()
    {
        // Called once after all MSTest test methods have completed (optional)
    }
    

    The ClassInitialize method must be public, static, return void and takes a single parameter. The ClassCleanup method must be public, static, return void and takes no parameters.

    For NUnit, the attribute references can be found here:

    [OneTimeSetUp]
    public void TestFixtureSetup()
    {
        // Called once before any NUnit test method has started (optional)
    }
    
    [OneTimeTearDown]
    public void TestFixtureTearDown()
    {
        // Called once after all NUnit test methods have completed (optional)
    }
    

    The OneTimeSetUp method must be public, but can be static or an instance method. Same for the OneTimeTearDown method.

    xUnit does not appear to support the Setup / Teardown feature.