Visual Studio Unit tests: run initialization code before each test

5.5k Views Asked by At

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
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

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
3
On

It is [TestInitialize] but you have the syntax wrong, it doesn't take a context:

[TestInitialize]
public static void InitializeTests()
{
    //... code that runs before each test
}