Visual Studio Unit tests: run initialization code before each test

I use Visual Studio testing tools for unit testing. I need an initialization code to run before each test .

I have a class Setupfor initialization code. I have 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 attribute [TestInitialize], but this only applies to tests in the same file as the method [TestInitialize]. I would like the initialization code to run automatically for all tests in the assembly, without explicitly invoking it in each 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
    }
}
+4
2

( , ):

  • DatabaseIntegrationTests TestInitialize
+6

is [TestInitialize], , :

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

All Articles