我們?cè)傩略鲆粋(gè)方法:
[TearDown]
public void FinalizeMethod()
{
Console.WriteLine("Finalize method");
}
再來看運(yùn)行NUnit的結(jié)果:
知道了[SetUp]和[TearDown]后,我們可以改寫這個(gè)單元測(cè)試類了。
請(qǐng)[TestFixture]
public class CalculatorTest
...{
private Calculator cal;
private int a, b, expected, actual;
[SetUp]
public void InitMethod()
...{
cal = new Calculator();
a = 10;
b = 2;
}
[Test]
public void TestAdd()
...{
expected = 12;
actual = cal.Add(a, b);
Assert.AreEqual(expected, actual);
}
[Test]
public void TestMinus()
...{
expected = 8;
actual = cal.Minus(a, b);
Assert.AreEqual(expected, actual);
}
[Test]
public void TestMultiply()
...{
expected = 20;
actual = cal.Multiply(a, b);
Assert.AreEqual(expected, actual);
}
[Test]
public void TestDivide()
...{
expected = 5;
actual = cal.Divide(a, b);
Assert.AreEqual(expected, actual);
}
}
因?yàn)檫\(yùn)行每個(gè)測(cè)試方法之前,都會(huì)運(yùn)行InitMethod()方法,所以每次都會(huì)初始化使第一個(gè)操作數(shù)為10,第二個(gè)操作數(shù)為2。在[SetUp]中初始化了的資源,我們可以在[TearDown]里銷毀釋放。