我一直在考虑单元测试以及如何提高单元测试的可读性。我想为什么不给单元测试中的类提供一个字符来澄清它们的作用。
这是我写的一个简单的单元测试:
[TestFixture]
public class when_dave_transfers_money_from_wamu_account_to_the_woodforest_account
{
[Test]
public void should_increase_the_amount_in_woodforest_account_when_transaction_successfull()
{
Dave dave = new Dave();
Wamu wamu = new Wamu();
wamu.Balance = 150;
wamu.AddUser(dave);
Woodforest woodforest = new Woodforest();
woodforest.AddUser(dave);
FundTransferService.Transfer(100, wamu, woodforest);
Assert.AreEqual(wamu.Balance, 50);
Assert.AreEqual(woodforest.Balance, 100);
}
}
这是Dave课程:
/// <summary>
/// This is Dave!
/// </summary>
public class Dave : User
{
public Dave()
{
FirstName = "Dave";
LastName = "Allen";
}
}
单元测试名称明确用于此目的。但是,也许我想深入挖掘并在Dave创建时将Wamu和Woodforest帐户分配给Dave。问题是它将远离可读性,因为我将不得不使用索引值来引用帐户。
您对使其更具可读性有何看法?
答案 0 :(得分:2)
测试夹具中的私有辅助方法怎么样
private Dave GetDave_With_Wamu_And_Woodforest_AccountsHookedUp()
答案 1 :(得分:1)
这是运行测试的另一种方法:
[Test]
public void should_increase_the_amount_in_woodforest_account_when_transaction_successfull()
{
Dave dave = new Dave();
// we know that dave has wamu and wooforest accounts
dave.WamuAccount("Wamu").Balance = 150;
FundTransferService.Transfer(100, dave.WamuAccount("Wamu"), dave.WoodforestAccount(
"Woodforest"));
Assert.AreEqual(50, dave.WamuAccount("Wamu").Balance);
Assert.AreEqual(100, dave.WoodforestAccount("Woodforest").Balance);
}
答案 2 :(得分:0)
当像这样创建Dave时,我可以将Dave添加到Wamu和Woodforest帐户:
public Dave()
{
FirstName = "Dave";
LastName = "Allen";
// add accounts for Dave
Wamu wamu = new Wamu();
wamu.AddUser(this);
Woodforest woodforest = new Woodforest();
woodforest.AddUser(this);
}
将帐户添加到Dave继承的User对象中的List集合中。
答案 3 :(得分:0)
当您尝试实例化Wamu实例时,是否应该抛出WamuNotFoundException?