我的公司在單元測試中,我在重構服務層代碼時遇到了一些問題。下面是一些代碼,我寫了一個例子:重構服務層類
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額外的課程。我們只在一個地方計算髮票,因此這些部分不會真正可重複使用。這是做出這個改變的正確方法,還是你建議我做一些不同的事情?
謝謝!
Jess
我們所有的實體對象基本都是DTO,所以所有的業務邏輯都在服務類中。但是在發票行計算器中有很多其他邏輯,我只是展示了一件。 – 2010-01-24 21:19:19