Unit Testing method independence
So, I was not totall开发者_如何学JAVAy sure this was true:
[TestClass]
public class UnitTest1
{
private int i = 0;
[TestMethod]
public void TestMethod1()
{
Thread.Sleep(5000);
Assert.IsTrue(i == 10);
}
[TestMethod]
public void TestMethod2() {
i = 10;
}
}
By the results of the test, it looks like it isn't, but I'd like to know for sure that if I define a global variable on a Test Method, it can't be read by other Test Methods.
Also, do I have to define
[TestCleanup]
public void Test_Cleanup() {
engine = null;
}
becase of this
[TestInitialize]
public void Test_Initialize()
{
var pieceGeneratorMock = new Mock<IPieceGenerator>();
pieceGeneratorMock.Setup(pg => pg.Generate())
.Returns(new Piece(Color.Red));
IPieceGenerator pieceGenerator = pieceGeneratorMock.Object;
Size size = new Size(4, 4);
BackgroundBoard backgroundBoard = new BackgroundBoard(size);
PieceBoard pieceBoard = new PieceBoard(size);
engine = new Engine(pieceGenerator, backgroundBoard, pieceBoard);
}
?
In JUnit, at least, each test method is invoked on a separate instance of your TestCase. You could verify this for yourself by outputting/logging the indentity hash of this
in each test* method.
You can use global variables inside test classes. There is a fundamental principle that each test that you write should be independent. Ideally there should not be dependencies between two test methods. If you want to use global variables you could initialize them inside the method which is decorated with [TestInitialize] attribute. This method is called everytime before executing any test method which are decorated with [TestMethod] attribute.
This allows you to share a variable across test methods but ensures that it is always set to a particular value before executing the test. You can find more about this on my blog at comparing unit testing framework
Inside of a test class the member behaviour is the same as any other class. The class is not reconstructed for each test method call, so the member values are continued, though there are TestCleanup and TestInitialize attributes you can use for methods to be run inbetween your testmethods.
TestCleanup and TestInitialize are not needed because of eachother, they can be used together or mutually exclusively. TestInitialize will be run before each test, TestCleanup will be run after every test (but before the Testinitialize). Pretty straight forward.
You can and should use setUp and tearDown methods to initialize and clean up before and after your tests.
That said, I think every test runs on its own object; i.e. there is a new UnitTest1 object for every test execution.
You aren't forking the TestMethod1(), so the whole thread is waiting until the sleep period is over, running the assert, and finding it false because the thread hasn't reached TestMethod2
And to answer your question, both methods can read and write i.
精彩评论