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給我們提供了一個功能強大,操作簡單的單元測試功能。利用該功能,程序員在編寫代碼后,可以馬上對所編寫的類進行單元測試,通過了程序員自行組織的單元測試后再將代碼交給測試人員進行進一步測試。