MsTest - executing method before each test in an assembly

后端 未结 5 1554
青春惊慌失措
青春惊慌失措 2021-02-06 21:45

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\'

5条回答
  •  感动是毒
    2021-02-06 22:25

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

提交回复
热议问题