Search code examples
c#visual-studiounit-testingvisualstudio.testtools

Visual Studio Unit tests: run initialization code before each test


I'm using Visual Studio's Test Tools for unit testing. I need some initialization code to run before each test.

I have a Setup class for the initialization code. I already added code to run before each test run, using [AssemblyInitialize], but I can't figure out how to do the same on a single test basis.

I tried using the [TestInitialize] attribute, but this only applies to tests in the same file as the [TestInitialize] method. I would like the initialization code to run automatically for all tests in the assembly, without having to explicitly call it in each and every test file.

[TestClass]
public class Setup
{
    [AssemblyInitialize]
    public static void InitializeTestRun(TestContext context)
    {
        //... code that runs before each test run
    }

    [TestInitialize] //this doesn't work!
    public static void InitializeTest()
    {
        //... code that runs before each test
    }
}

Solution

  • The following should work (at least it works with other test frameworks):

    • Create a base class DatabaseIntegrationTests with the TestInitialize method
    • Derive your other Testclasses from that base class