Search code examples
c#unit-testingstaticvs-unit-testing-framework

How do I run unit tests in VS based on different values of a static variable?


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?


Solution

  • 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());
            }
        }