测试装置示例
请考虑以下针对 BankAccount 类的类关系图,以及一个示例测试装置 (BankAccountTests.cs)。
图 1. BankAccount 类
示例测试装置: BankAccountTests.cs
using BankAccountDemo.Business;
using Microsoft.VisualStudio.QualityTools.UnitTesting.Framework;
namespace BankAccountDemo.Business.Tests
{
[TestClass()]
public class BankAccountTest
{
[TestInitialize()]
public void Initialize() {
}
[TestCleanup()]
public void Cleanup() {
}
[TestMethod()]
public void ConstructorTest() {
float currentBalance = 500;
BankAccount target = new BankAccount(currentBalance);
Assert.AreEqual(currentBalance, target.CurrentBalance,
"Balances are not equal upon creation");
}
[TestMethod()]
public void DepositMoneyTest() {
float currentBalance = 500;
BankAccount target = new BankAccount(currentBalance);
float depositAmount = 10;
target.DepositMoney(depositAmount);
Assert.IsTrue( (currentBalance + depositAmount) >
target.CurrentBalance,
"Deposit not applied correctly");
}
[TestMethod()]
public void MakePaymentTest() {
float currentBalance = 500;
BankAccount target = new BankAccount(currentBalance);
float paymentAmount = 250;
target.MakePayment(paymentAmount);
Assert.IsTrue(currentBalance - paymentAmount ==
target.CurrentBalance,
"Payment not applied correctly");
}
}
}
主单元测试概念 == 断言
用于该形式单元测试的主要概念是,自动化单元测试是基于“断言”的,即可定义为“事实或您相信为事实的内容”。从逻辑角度看,请考虑该语句“when I do {x}, I expect {y} as a result”。
这可以轻松地翻译为代码,方法是使用 Microsoft.VisualStudio.QualityTools.UnitTesting.Framework 命名空间中可用的三个“断言”类中的任一个:Assert、StringAssert 和 CollectionAssert。主类 Assert 提供用于测试基础条件语句的断言。StringAssert 类自定义了在使用字符串变量时有用的断言。同样,CollectionAssert 类包括在使用对象集合时有用的断言方法。
表 3 显示可用于当前版本 Unit Testing Framework 的断言。
表 3. VSTS Unit Testing Framework 断言
断言类 StringAssert 类 CollectionAssert 类
AreEqual()
AreNotEqual()
AreNotSame()
AreSame()
EqualsTests()
Fail()
GetHashCodeTests()
Inconclusive()
IsFalse()
IsInstanceOfType()
IsNotInstanceOfType()
IsNotNull()
IsNull()
IsTrue()
Contains()
DoesNotMatch()
EndsWith()
Matches()
StartsWith()
AllItemsAreInstancesOfType()
AllItemsAreNotNull()
AllItemsAreUnique()
AreEqual()
AreEquivalent()
AreNotEqual()
AreNotEquivalent()
Contains()
DoesNotContain()
IsNotSubsetOf()
IsSubsetOf()