Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing MSTest to use a single thread

Given this test fixture:

[TestClass] public class MSTestThreads {     [TestMethod]     public void Test1()     {         Trace.WriteLine(Thread.CurrentThread.ManagedThreadId);     }      [TestMethod]     public void Test2()     {         Trace.WriteLine(Thread.CurrentThread.ManagedThreadId);     } } 

Running the test with MSTest through Visual Studio or command line prints two different thread numbers (yet they are run sequentially anyway).

Is there a way to force MSTest to run them using a single thread?

like image 251
Paul Stovell Avatar asked Feb 18 '11 03:02

Paul Stovell


People also ask

How do I run a single unit test in Visual Studio?

Run tests in Test Explorer If Test Explorer is not visible, choose Test on the Visual Studio menu, choose Windows, and then choose Test Explorer (or press Ctrl + E, T). As you run, write, and rerun your tests, the Test Explorer displays the results in a default grouping of Project, Namespace, and Class.

Does MSTest support .NET core?

Cross-Platform support – V2 version of the MSTest framework is a cross-platform implementation of the framework using which developers can write tests targeting . NET Framework, . NET Core, and ASP.NET Core on platforms like Linux, Mac, and Windows.


2 Answers

I've fought for endless hours to make MSTest run in a single threaded mode on a large project that made heavy use of nHibernate and it's not-thread-safe (not a problem, it's just not) ISession.

We ended up more time writing code to support the multi-threaded nature of MSTest because - to the best of my and my teams knowledge - it is not possible to run MSTest in a single threaded mode.

like image 35
detroitpro Avatar answered Sep 28 '22 23:09

detroitpro


I solved this problem with locking:

public static class IntegrationTestsSynchronization {     public static readonly object LockObject = new object(); } 

[TestClass] public class ATestCaseClass {     [TestInitialize]     public void TestInitialize()     {         Monitor.Enter(IntegrationTestsSynchronization.LockObject);     }      [TestCleanup]     public void TestCleanup()     {         Monitor.Exit(IntegrationTestsSynchronization.LockObject);     }      //test methods }  // possibly other test cases 

This can of course be extracted to a base test class and reused.

like image 102
BartoszKP Avatar answered Sep 29 '22 00:09

BartoszKP