看看我们的测试代码,我们可以看到一些适宜的重构。所有的方法共享一组公共的测试对象。让我们来将这些初始化代码放到一个setup方法中并在所有的测试中重用它们。我们的测试类的重构版本像下面这样:
namespace bank {
using System;
using NUnit.Framework;
[TestFixture]
public class AccountTest {
Account source;
Account destination;
[SetUp]
public void Init() {
source = new Account();
source.Deposit(200.00F);
destination = new Account();
destination.Deposit(150.00F);
}
[Test]
public void TransferFunds() {
source.TransferFunds(destination, 100.00f);
Assert.AreEqual(250.00F, destination.Balance);
Assert.AreEqual(100.00F, source.Balance);
}
[Test]
[ExpectedException(typeof(InsufficientFundsException))]
public void TransferWithInsufficientFunds() {
source.TransferFunds(destination, 300.00F);
}
[Test,
Ignore (
"Need to decide how to implement transaction management in the application"
)]
public void TransferWithInsufficientFundsAtomicity() {
try {
source.TransferFunds(destination, 300.00F);
}
catch(InsufficientFundsException expected) {
}
Assert.AreEqual(200.00F,source.Balance);
Assert.AreEqual(150.00F,destination.Balance);
}
}
}
注意这个初始化方法拥有通用的初始化代码,它的返回值类型为void,没有参数,并且由[SetUp]特性标记。编译并运行——同样的黄条!
======全文完==========
如果你安装了NUnit V2.1,可以在 开始->程序->NUnit V2.1->QuickStart 处得到原文(英文版)。