[ClassInitialize()] [ClassCleanup()] [TestInitialize()] [TestMethod] [TestCleanup()]
在执行一个或多个[TestMethod]输出时, [ClassInitialize()] 最先执行,[ClassCleanup()]最后执行,对于执行每个[TestMethod],执行顺序是[TestInitialize()] [TestMethod] [TestCleanup()]
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { static StreamWriter sw = new StreamWriter("C:\\temp\\Test.txt", false); [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { sw.WriteLine("MyClassInitialize"); sw.Flush(); } [ClassCleanup()] public static void MyClassCleanup() { sw.WriteLine("MyClassCleanup"); sw.Flush(); } [TestInitialize()] public void MyTestInitialize() { sw.WriteLine("MyTestInitialize"); sw.Flush(); } [TestCleanup()] public void MyTestCleanup() { sw.WriteLine("MyTestCleanup"); sw.Flush(); } [TestMethod] public void TestMethod1() { sw.WriteLine("TestMethod1"); sw.Flush(); } [TestMethod] public void TestMethod2() { sw.WriteLine("TestMethod2"); sw.Flush(); } [TestMethod] public void TestMethod3() { sw.WriteLine("TestMethod3"); sw.Flush(); } } }
3个method一起选中执行的输出
MyClassInitialize
MyTestInitialize
TestMethod1
MyTestCleanup
MyTestInitialize
TestMethod2
MyTestCleanup
MyTestInitialize
TestMethod3
MyTestCleanup
MyClassCleanup
选中一个,执行后的输出
MyClassInitialize
MyTestInitialize
TestMethod1
MyTestCleanup
MyClassCleanup