简体   繁体   中英

How can I prevent my NUnit tests from running in parallel sometimes

I'm using the NUnit test runner included in Monodevelop. I have 2 tests which must interact with static resources so I need them to run serially rather than parallel. I've tried using something like

static string Locker="foo";
[Test]
public void Test1()
{
  lock(Locker)
  {
    //....
  }
}
[Test]
public void Test2()
{
  lock(Locker)
  {
    //....
  }
}

This doesn't seem to work though. Is there some other way?

I'm using this approach when REALLY needed (i think it's a bad idea):

using System.Threading;
private ManualResetEvent FixtureHandle = new ManualResetEvent(true);
[SetUp]
public void SetUp()
{
    FixtureHandle.WaitOne();
}
[TearDown]
public void TearDown()
{
    FixtureHandle.Set();
}
[Test]
public void Test1()
{
  //only test
}
[Test]
public void Test2()
{
  //only test
}

Dont know about Monodevelop but nunit console has command line argument /nothread

It should be something similar in Monodevelop i think

Instead of using the static resource directly, extract that into a dependency, and mock it (using moq or something similar).

That will let you write actual unit tests that isolate the specific piece of code you are trying to test without worrying about external context.

For running tests serially it's best to use the Order attribute:

static string Locker="foo";
[Test, Order(1)]
public void Test1()
{
  lock(Locker)
  {
    //....
  }
}
[Test, Order(2)]
public void Test2()
{
  lock(Locker)
  {
    //....
  }
}

You are missing the point of the Unit Testing. The Unit tests must be independent in every way.

This means that the execution order must not influence the Unit Tests results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM