【发布时间】:2010-07-21 21:19:55
【问题描述】:
我有一个应用程序服务(即大型方法)负责协调多个业务对象之间的交互。本质上,它从一个包含客户信息和发票的系统中获取 DTO,然后根据各种业务规则将其翻译并导入到不同的系统中。
public void ProcessQueuedData()
{
var queuedItems = _importServiceDAL.LoadQueuedData();
foreach (var queuedItem in queuedItems)
{
var itemType = GetQueuedImportItemType(queuedItem);
if (itemType == QueuedImportItemType.Invoice)
{
var account = _accountDAL.GetAccountByAssocNo(queuedItem.Assoc);
int agentAccountID;
if (!account.IsValid)
{
agentAccountId = _accountDAL.AddAccount(queuedItem.Assoc);
}
else
{
agentAccountId = account.AgentAccountID;
}
/// Do additional processing TBD
}
}
}
对于单元测试,假设服务中的整个过程应该在粒度的基础上逐步测试是否正确,类似于以下内容?
ImportService_ProcessQueuedData_CallsDataAccessLayer_ToLoadQueue
ImportService_ProcessQueuedData_WithQueuedItemToProccess_ChecksIfAccountExists
ImportService_ProcessQueuedData_WithInvoice_CallsDALToCreateAccountIfOneDoesNotExist
这是一个典型的测试:
[TestMethod()]
public void ImportService_ProcessQueuedData_WithInvoice_CallsDALToCheckIfAgentAccountExists()
{
var accountDAL = MockRepository.GenerateStub<IAccountDAL>();
var importServiceDAL = MockRepository.GenerateStub<IImportServiceDAL>();
importServiceDAL.Stub(x => x.LoadQueuedData())
.Return(GetQueuedImportItemsWithInvoice());
accountDAL.Stub(x => x.GetAccountByAssocNo("FFFFF"))
.IgnoreArguments()
.Return(new Account() { AgentAccountId = 0 });
var importSvc = new ImportService(accountDAL, importServiceDAL);
importSvc.ProcessQueuedData();
accountDAL.AssertWasCalled(a => a.GetAccountByAssocNo("FFFFF"), o => o.IgnoreArguments());
accountDAL.VerifyAllExpectations();
}
我的问题是,我最终在每个测试中都进行了如此多的设置,它变得脆弱。这是正确的方法吗?如果是的话,有什么建议可以避免在每个细粒度测试中重复所有这些设置?
【问题讨论】:
标签: c# unit-testing testing methods