时间:2021-07-01 10:21:17 帮助过:41人阅读
NUnit Quick Start
原文档:http://www.nunit.org
翻 译:Young.J
说 明:该实例是最早期的nunit版本中找到,在测试驱动的开发中它并不是一个很好的例子,但它能阐明使用nunit的最基本方法。
现在开始我们的例子。假设我们开始写一个银行业的应用程序,我们有一个基类—Account,Account主要负责资金的增加,撤销和转帐,下面是该类的代码
1
namespace bank

{
public class Account
{
private float balance;
public void Deposit(float amount)
{
balance+=amount;
}
public void Withdraw(float amount)
{
balance-=amount;
}
public void TransferFunds(Account destination, float amount)
{ }
public float Balance
{ 
get
{ return balance;}
}
}
} 在我们来写一个需要测试的类—AccountTest,我们第一个测试的方法是TransferFunds
1
namespace bank

{
using NUnit.Framework;
[TestFixture]
public class AccountTest
{
[Test]
public void TransferFunds()
{
Account source = new Account();
source.Deposit(200.00F);
Account destination = new Account();
destination.Deposit(150.00F);
source.TransferFunds(destination, 100.00F);
Assert.AreEqual(250.00F, destination.Balance);
Assert.AreEqual(100.00F, source.Balance);
}
}
} 现在做的第一件事是声明这个类有一个[TestFixture]属性,通过这种方法显示这个类包含测试代码(此属性可以被继承),这个类必须是public类且其派生内没有限制,这个类当然必须有一个默认构造函数。
public void TransferFunds(Account destination, float amount)

{
destination.Deposit(amount);
Withdraw(amount);
} 现在我们再次编译代码,并在GUI中运行,我们何以看到测试条变绿!测试成功!
private float minimumBalance = 10.00F;
public float MinimumBalance

{
get
{ return minimumBalance;}
} 增加一个表明透支的异常;
1
public class InsufficientFundsException : ApplicationException

{
} 增加一个测试方法到AccountTest类中
1
[Test]
[ExpectedException(typeof(InsufficientFundsException))]
public void TransferWithInsufficientFunds()

{
Account source = new Account();
source.Deposit(200.00F);
Account destination = new Account();
destination.Deposit(150.00F);
source.TransferFunds(destination, 300.00F);
} 这个测试方法的[Test]属性有一个 [ExpectedException]属性,这表明这段测试代码期望得到某一类型的异常,如果这种异常没有出现在执行过程中,这车是失败,现在编译代码,启动NUnit Gui,这是测试条变红,提示错误信息:
public void TransferFunds(Account destination, float amount)

{
destination.Deposit(amount);
if(balance-amount < minimumBalance)
throw new InsufficientFundsException();
Withdraw(amount);
} 编译,运行测试-测试条变绿,成功了,但是,我们看看这个代码,我们仅仅写了我们可以看到的转帐操作中的错误,现在让我们来写一个测试来证实我们不确定的错误,添加下面一个测试方法
1