MsTest - executing method before each test in an a

2020-05-29 15:49发布

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.

标签: .net mstest
5条回答
Explosion°爆炸
2楼-- · 2020-05-29 15:52

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

查看更多
成全新的幸福
3楼-- · 2020-05-29 15:58

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... :)

查看更多
贼婆χ
4楼-- · 2020-05-29 16:03

I think you are looking for the ClassInitialize attribute.

查看更多
聊天终结者
5楼-- · 2020-05-29 16:06

You want to use [AssemblyInitialize].

See: MSDN Link

or this question: on stackoverflow

查看更多
等我变得足够好
6楼-- · 2020-05-29 16:07

Well isn't MSTest instantiating the class for each test? That was my understanding of it. In such a case whatever you call from your constructor is the initialization code (per test by definition).

EDIT: If it doesn't work (which I still think it should because MSTest needs to make sure that individual test method runs are isolated) then TestInitialize is your attribute. By the way the best unit-test comparison is available at Link on Codeplex

查看更多
登录 后发表回答