Mark Oliver's World

Posted: 08/04/2024

Forcing Tests To Run In A Specific Order Using MSTest

By default, MSTest will run all tests in alphabetical order based on their name.

This means, you should be able to know when a test will run in relation to another.

For example, if you prefix your tests with TXXX, where XXX is the test number:

            T001_test_something T002_test_something_else T003_third_test_to_be_executed
            
          

Then these tests will (by default) run T001 first, followed by T002, T003 etc...

Watch out though, the ordering is based on string comparison, so a test named T010 will run before T002!

But you can run them in your own order without changing the name, and that is to use the Priority attribute

Add this to the top of each TestMethod you wish to define an order of e.g.

            [TestMethod, Priority(1)] public async Task ATestThatWillRunFirst() {     // Arrange     // Act     // Assert }  [TestMethod, Priority(2)] public async Task AnotherTestThatWillRunSecond() {     // Arrange     // Act     // Assert }
            
          

I don't recommend this approach, as any test should be atomic, and therefore not matter what order they are run in.

In fact this is vitally important if you are running tests in parallel!

BUT there may be an odd occasion you want them to run in a specific order, such as complex Integration Tests that require significant setup, and so this can be useful.


Thanks for reading this post.

If you want to reach out, catch me on Twitter!

I am always open to mentoring people, so get in touch.