MsTest - executing method before each test in an assembly

[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.


I am not sure that this feature is possible in MsTest out of box like in other test frameworks (e.g. MbUnit).

If I have to use MsTest, then I am solving this by defining abstract class TestBase with [TestInitialize] attribute and every test which needs this behaviour derives from this base class. In your case, every test class in your assembly must inherit from this base...

And there is probably another solution, you can make your custom test attribute - but I have not tried this yet... :)

Tags:

.Net

Mstest