0

I am trying to write a unit test to make sure the results of a method are correct based on different values of a static variable.

Here is a simple example:

public void TestMethod1()
{
     Object1.StaticMember = 1
     Object2 test = new Object2();
     Assert.AreEqual("1", test.getStaticVal());
}

public void TestMethod2()
{
     Object1.StaticMember = 2
     Object2 test = new Object2();
     Assert.AreEqual("2", test.getStaticVal());
}

I was informed that unit tests in VS2012 are excecuted concurrently so there is a posibility of the tests failing. Is this true? How can I write the tests to run one at a time?

dspiegs
  • 548
  • 2
  • 9
  • 24
  • possible duplication http://stackoverflow.com/questions/10632975/static-class-method-property-in-unit-test-stop-it-or-not. – Mzf Jun 06 '13 at 21:59
  • Really so is that means these two test repeatedly pass in VS2010? Is there more reference detail I can read about the VS2012 concurrency tests running? – Spock Jun 07 '13 at 00:28

1 Answers1

3

There is probably a more elegant way to do it but you can always use a lock object like this...

    private static Object LockObject = new object();

    public void TestMethod1()
    {
        lock(LockObject)
        {
            Object1.StaticMember = 1;
            Object2 test = new Object2();
            Assert.AreEqual("1", test.getStaticVal());
        }
    }

    public void TestMethod2()
    {
        lock (LockObject)
        {
            Object1.StaticMember = 2;
            Object2 test = new Object2();
            Assert.AreEqual("2", test.getStaticVal());
        }
    }
Kevin
  • 4,586
  • 23
  • 35