利用Visual Studio 2008来进行单元测试
假设我们有一个类BankAccount,该类定义了一个银行的账户,私有属性_currentBalance是银行储户的账户金额,depositMoney是存款方法,对帐户增加一笔资金,makePayment是支付方法,对账户减少一笔资金。代码如下:
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BankAccountDemo.Business
...{
class BankAccount
...{
private float _currentBalance;
public float CurrentBalance
...{
get ...{ return _currentBalance; }
set ...{ _currentBalance = value; }
}
public BankAccount(float initialBalance)
...{
this._currentBalance = initialBalance;
}
public void depositMoney(float depositAmount)
...{
this._currentBalance += depositAmount;
}
public void makePayment(float paymentAmount)
...{
this._currentBalance -= paymentAmount;
}
}
}
要对BankAccount类进行单元测试,只需要在BankAccount的定义处鼠标右键,在菜单中选择“Create Unit Tests”即可进入测试项目的创建工作。如下图所示:

在弹出的创建单元测试的对话框中,对需要创建测试的方法和属性进行选择,然后点击“OK”按钮,如图所示:
紧接着在出现的文本框中输入测试项目的名称“BankAccountDemo.Business.Tests”,点击确定后,测试项目被创建。在这里“BankAccountDemo.Business.”只是用于更好的对命名空间进行规划,完全可以直接使用“BankAccountDemoTest”来作为测试项目的名字。
生成的测试代码如下,为了紧凑的表现代码,将注释代码作了删除。
这个时候的代码并不能开始测试,而需要我们按照测试用例的要求将测试用例的数据加入到测试方法中,并进行结果的比较,修改后的depositMoneyTest方法如下:
public void depositMoneyTest()
{
float initialBalance = 0F; // TODO: Initialize to an appropriate value
BankAccount target = new BankAccount(initialBalance); // TODO: Initialize to an appropriate value
float depositAmount = 100F; // TODO: Initialize to an appropriate value
target.depositMoney(depositAmount);
Assert.AreEqual(initialBalance + depositAmount, target.CurrentBalance, "Deposit Test: Deposit not applied correctly");
}
鼠标右键在depositMoneyTest方法内任意位置单击,在弹出的菜单中选择“Run Tests”,即可以对该方法进行测试。在“Test Results”窗口中显示测试的结果,如下图所示:

可以看出,Visual Studio 2008给我们提供了一个功能强大,操作简单的单元测试功能。利用该功能,程序员在编写代码后,可以马上对所编写的类进行单元测试,通过了程序员自行组织的单元测试后再将代码交给测试人员进行进一步测试。