Martin Fowler的《重构》这本书基本上每个程序员都会看,对于做单元测试的测试工程师来说,测试的代码本身也是程序,也需要重构。最近在看《XUnit Test Patterns》,把以前的做的东西重新梳理了一下,并且落实到新的项目中。
首先来看看一个最原始的单元测试代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[TestMethod]
public void GetPaymentAccountByOwnerID()
{
int ownerId = 1300100000;
//Delete the account
TestHelper.DeletePaymentAccountByOwnerId(ownerId);
//Here should be create an account
PaymentAccount paymentAccount = PaymentGateway.PaymentProvider.GetPaymentAccountByOwnerID(ownerId, AccountOwnerType.NormalUser);
//Verify the payment account instance
Assert.IsTrue(paymentAccount.AccountID > 0);
Assert.AreEqual(DateTime.Now.DayOfYear, paymentAccount.CreateTime.DayOfYear);
Assert.AreEqual(DateTime.Now.DayOfYear, paymentAccount.UpdateTime.DayOfYear);
Assert.AreEqual(0, paymentAccount.Balance, 0.0001);
Assert.AreEqual(0, paymentAccount.AvailableBalance, 0.0001);
Assert.AreEqual(0, paymentAccount.FreezeAccount, 0.0001);
}
以上是个很简单的单元测试代码,应用了AAA原则,首先做好准备(删掉原有的数据),然后执行测试,最后再验证返回结果。看起来很好也很清晰。首先发现一个问题,就是那一堆Assert让人觉得迷惑,究竟想干啥?其实那6句Assert都是验证程序返回的PaymentAccount对象是是否符合设计。我把这些Assert语句提取出来,作为一个方法,让测试代码更加容易让人明白。也就有了版本2。