【发布时间】:2010-01-24 20:33:26
【问题描述】:
我的公司正在进行单元测试,我在重构服务层代码时遇到了一些麻烦。这是我编写的一些代码的示例:
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 个私有方法的 1,000 行类减少),我的老板说我应该能够分别测试我的 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 个额外的类。我们只在一个地方计算发票,所以这些部分真的不能重复使用。这是进行此更改的正确方法,还是建议我做一些不同的事情?
谢谢!
杰斯
【问题讨论】:
标签: c# unit-testing refactoring