Visual-studio – How to persist variables between tests in MSTest

mstestunit testingvisual studio

I'm using MSTest (VS2008) and I need to persist a variable between tests. However the variable gets re-initialized between every test.

According to the third point mentioned in this answer,

MSTest always instantiates a new instance of the test class for each test method being executed.

Is there a straightforward way to keep the value of a variable between tests, or somehow suppress this behaviour?

Best Answer

Use a static member variable:

static int _test = 0;

[TestMethod]
public void __Test1()
{
    _test += 1;
    Assert.IsTrue(_test == 1);
}

[TestMethod]
public void __Test2()
{
    _test += 1;
    Assert.IsTrue(_test == 2);
}