我们再新增一个方法:
[TearDown]
public void FinalizeMethod()
{
Console.WriteLine("Finalize method");
}
再来看运行NUnit的结果:
知道了[SetUp]和[TearDown]后,我们可以改写这个单元测试类了。
请[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);
}
}
因为运行每个测试方法之前,都会运行InitMethod()方法,所以每次都会初始化使第一个操作数为10,第二个操作数为2。在[SetUp]中初始化了的资源,我们可以在[TearDown]里销毁释放。