NUnit Quick Start
原文档:http://www.nunit.org
翻 译:Young.J
说 明:该实例是最早期的nunit版本中找到,在测试驱动的开发中它并不是一个很好的例子,但它能阐明使用nunit的最基本方法。
现在开始我们的例子。假设我们开始写一个银行业的应用程序,我们有一个基类—Account,Account主要负责资金的增加,撤销和转帐,下面是该类的代码
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;}
}
}
}
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);
}
}
}
public void TransferFunds(Account destination, float amount)

{
destination.Deposit(amount);
Withdraw(amount);
}
private float minimumBalance = 10.00F;
public float MinimumBalance

{
get
{ return minimumBalance;}
}
public class InsufficientFundsException : ApplicationException

{
}
[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);
}
public void TransferFunds(Account destination, float amount)

{
destination.Deposit(amount);
if(balance-amount < minimumBalance)
throw new InsufficientFundsException();
Withdraw(amount);
}
[Test]
public void TransferWithInsufficientFundsAtomicity()

{
Account source = new Account();
source.Deposit(200.00F);
Account destination = new Account();
destination.Deposit(150.00F);
try
{
source.TransferFunds(destination, 300.00F);
}
catch(InsufficientFundsException expected)
{
}
Assert.AreEqual(200.00F,source.Balance);
Assert.AreEqual(150.00F,destination.Balance);
}
[Test]
[Ignore("Decide how to implement transaction management")]
public void TransferWithInsufficientFundsAtomicity()

{
// code is the same
}