简体   繁体   中英

What is the scope of a test class when running unit tests?

When Visual Studio is running unit tests, it runs many tests simultaneously. What exactly is the scope of the test class while these are running. Are they all run in separate app domains or is data shared at all?

For instance if I have the following test class:

[TestClass]
public class FooTests
{
    Mock<ISomeInterface1> _complexMock1;
    Mock<ISomeInterface2> _complexMock2;

    public void CreateComplexMocks()
    {
        //set up _complexMock1 & _complexMock2
    }

    [TestMethod]
    public void Test1()
    {
        CreateComplexMocks();

        //use _complexMock1 & _complexMock2 in test
    }

    [TestMethod]
    public void Test2()
    {
        CreateComplexMocks();

        //use _complexMock1 & _complexMock2 in test
    }
}

The tests utilise the CreateComplexMocks() helper to construct some mocks. These are exposed as members rather than being passed back to the test (there would probably be many more in a real world example)

My question is, if both tests run at the same time, will they be sharing the state of _complexMock1 and _complexMock2 ?

What if the complexMocks were static?

Having found this blog , it would appear that a separate test class is instantiated for every test, on a different thread.

So instance members will not be shared, but static members will.

In your example you should create your mocks in the [TestInitialize] method.
By this every time a test would run your mocks would be created again.

[TestInitialize]
public void TestInit()
{
    CreateComplexMocks();
}

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