using System;
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;
}
}
}
MILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">
要对BankAccount类进行单元测试,只需要在BankAccount的定义处鼠标右键,在菜单中选择“Create Unit Tests”即可进入测试项目的创建工作。如下图所示:
紧接着在出现的文本框中输入测试项目的名称“BankAccountDemo.Business.Tests”,点击确定后,测试项目被创建。在这里“BankAccountDemo.Business.”只是用于更好的对命名空间进行规划,完全可以直接使用“BankAccountDemoTest”来作为测试项目的名字。
生成的测试代码如下,为了紧凑的表现代码,将注释代码作了删除。
这个时候的代码并不能开始测试,而需要我们按照测试用例的要求将测试用例的数据加入到测试方法中,并进行结果的比较,修改后的depositMoneyTest方法如下:
[TestMethod()]
public void depositMoneyTest()
{
float initialBalance =
BankAccount target = new BankAccount(initialBalance); // TODO: Initialize to an appropriate value
float depositAmount =
target.depositMoney(depositAmount);
Assert.AreEqual(initialBalance + depositAmount, target.CurrentBalance, "Deposit Test: Deposit not applied correctly");
}
可以看出,Visual Studio 2008给我们提供了一个功能强大,操作简单的单元测试功能。利用该功能,程序员在编写代码后,可以马上对所编写的类进行单元测试,通过了程序员自行组织的单元测试后再将代码交给测试人员进行进一步测试。