Jerther Jerther - 2 years ago 95
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

  • 2 - Randomly runs a

  • 3 - Runs the class

  • 4 - Randomly runs a
    from that class

  • 5 - Runs the class

  • Repeat 3 through 5 for each TestMethod in the class

  • Repeat 2 through 5 for each test class

  • 6 - Runs all classes

  • 7 - Runs

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.


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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download