Jerther Jerther - 22 days ago 6
C# Question

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

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.

Answer

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.