MsTest - executing method before each test in an assembly

brzozow picture brzozow · Mar 12, 2009 · Viewed 26.2k times · Source

Is it possible to run specific method before each test in an assembly?

I know about TestInitialize attribute but this attribute has "class scope". If it's defined in a Test class it will be executed before each test from this class.

I want to define a method that will be executed before each test defined in a whole assembly.

Answer

FryGuy picture FryGuy · Mar 13, 2009

[TestInitialize()] is what you need.

private string dir;

[TestInitialize()]
public void Startup()
{
    dir = Path.GetTempFileName();
    MakeDirectory(ssDir);
}

[TestCleanup()]
public void Cleanup()
{
    ss = null;
    Directory.SetCurrentDirectory(Path.GetTempPath());

    setAttributesNormal(new DirectoryInfo(ssDir));
    Directory.Delete(ssDir, true);
}


[TestMethod]
public void TestAddFile()
{
    File.WriteAllText(dir + "a", "This is a file");
    ss.AddFile("a");
    ...
}

[TestMethod]
public void TestAddFolder()
{
    ss.CreateFolder("a/");
    ...
}

This gives a new random temporary path for each test, and deletes it when it's done. You can verify this by running it in debug and looking at the dir variable for each test case.