What's the life cycle of Unit Tests in C#

2019-04-28 20:41发布

问题:

What's the sequence of events in a full MSTest run of unit tests in C# inside Visual Studio (Ctrl+R, A)?

Here's what I think so far:

  • 1 - Runs [AssemblyInitialize]
  • 2 - Randomly runs a [ClassInitialize]
  • 3 - Runs the class [TestInitialize]
  • 4 - Randomly runs a [TestMethod] from that class
  • 5 - Runs the class [TestCleanup]
  • Repeat 3 through 5 for each TestMethod in the class
  • Repeat 2 through 5 for each test class
  • 6 - Runs all classes [ClassCleanup] methods
  • 7 - Runs [AssemblyCleanup]

But I think VS might initialize multiple classes at once and then randomly run TestMethods. Should the tests be autonomous across its class or across the whole test project, or even the whole solution? Knowing the exact sequence of events should answer those questions.

UPDATE:

I did some tests and found that it is indeed the order in which events occurs, except for #3 to 5 where ANY test from ANY class could run. Visual Studio seems to sequentially run one test at a time. However, one should not rely on this for reasons explained in accepted answer.

回答1:

You are correct. This is indeed the order in which the code will be run. However, since tests should be completely independent, there are no guarantee that they will be run in order and that they will be run on a single thread. The framework could run multiple test at the same time.

You can force a specific test order through the use of test cases if you need too, but this is considered bad practice as test cases should be used to regroup tests together (tag them) instead.



回答2:

To define a specific order for your tests, either create an ordered test (http://msdn.microsoft.com/en-us/library/ms182631.aspx) or create a match file and call mstest.exe for each test case in the specified order you desire (http://msdn.microsoft.com/en-us/library/ms182489(VS.80).aspx)