我的公司正处于单元测试的热潮中,我在重构服务层代码时遇到了一些麻烦。下面是我写的一段代码示例:
public class InvoiceCalculator:IInvoiceCalculator
{
public CalculateInvoice(Invoice invoice)
{
foreach (InvoiceLine il in invoice.Lines)
{
UpdateLine(il);
}
//do a ton of other stuff here
}
private UpdateLine(InvoiceLine line)
{
line.Amount = line.Qty * line.Rate;
//do a bunch of other stuff, including calls to other private methods
}
}
在这个简化的情况下(它从一个有1个公共方法和约30个私有方法的1000行类中被缩减),我的老板说我应该能够分别测试我的CalculateInvoice和UpdateLine(UpdateLine实际上调用3个其他私有方法,并执行数据库调用)。但是我该如何做到呢?他建议的重构对我来说似乎有点复杂:
//Tiny part of original code
public class InvoiceCalculator:IInvoiceCalculator
{
public ILineUpdater _lineUpdater;
public InvoiceCalculator (ILineUpdater lineUpdater)
{
_lineUpdater = lineUpdater;
}
public CalculateInvoice(Invoice invoice)
{
foreach (InvoiceLine il in invoice.Lines)
{
_lineUpdater.UpdateLine(il);
}
//do a ton of other stuff here
}
}
public class LineUpdater:ILineUpdater
{
public UpdateLine(InvoiceLine line)
{
line.Amount = line.Qty * line.Rate;
//do a bunch of other stuff
}
}
我能看到现在依赖关系已经被打破了,我可以测试两个部分,但这也会从我的原始类中创建20-30个额外的类。我们只在一个地方计算发票,所以这些部分实际上并不可重用。这是进行此更改的正确方式吗?还是您建议我采取其他措施?
谢谢!
杰丝