MSTest executing all my tests simultaneously breaks tests - what to do

George Mauer picture George Mauer · Mar 31, 2009 · Viewed 9.2k times · Source

Ok, this is annoying.

MSTest executes all of my tests simultaneously which causes some of them to fail. No this is not because my tests are fragile and susceptible to build order rather it is because this is a demo project in which I use a Db4o object database running from a file.

So I have a couple of DataAccess tests checking that my repositories work correctly and boom, MSTest blows up. Since it tries to run all its tests at the same time it gets an error when a test tries to access the database file while other tests are using it.

Can anyone think of a quick way around this? I don't want to ditch MSTest (ok I do but another story) and I sure as heck don't want to run a full-blown database service so I'll take any way to force MSTest not to run simultaneously or tricks with opening files.

Anyone have any ideas?

Answer

tvanfosson picture tvanfosson · Mar 31, 2009

You might want to try using a Monitor and entering in TestInitialize and exiting on TestCleanup. If your test classes all depend on the external file, you'll need to use a single lock object for all of them.

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

...

[TestInitialize]
public void TestSetup()
{
     Monitor.Enter(LockClass.LockObject);
}

[TestCleanup]
public void TestCleanup()
{
     Monitor.Exit(LockClass.LockObject);
}

This should force all of your tests to run serially and as long as all of your tests pass/fail they should run. If any of them throws an unexpected exception, though, all the rest will hang since the Exit code won't be run for the test that blows up.