如果你正在做TDD,你應該將小步驟,專注於你的類應該做的事情。這裏是例子。你想打印一些報告。首先(我想你正在向外移動),你設計的課程Report
應該通過Printer
打印自己(這只是例子)。所以你寫測試:
[Test]
public void ShouldPrintItself()
{
Mock<IPrinter> printer = new Mock<IPrinter>();
Report report = new Report(printer.Object);
report.Text = "foo";
report.Print();
printer.Verify(p => p.Print("foo"));
}
然後你寫一些執行report.Print
方法。你現在正在設計IPrinter接口。接下來您瞭解打印機有時可能會顯示異常(例如紙張不足)。這是你的情況順便說一句。因此,重命名report.Print
方法類似TryPrint
,改變第一次測試,並建立新的:
[Test]
public void ShouldPrint()
{
Mock<IPrinter> printer = new Mock<IPrinter>();
Report report = new Report(printer.Object);
report.Text = "foo";
Assert.True(report.TryPrint());
printer.Verify(p => p.Print("foo"));
}
[Test]
public void ShouldNotPrint()
{
Mock<IPrinter> printer = new Mock<IPrinter>();
printer.Setup(p => p.Print(It.IsAny<string>())).Throws<Exception>();
Report report = new Report(printer.Object);
report.Text = "foo";
Assert.False(report.TryPrint());
}
,並返回到TryPrint
方法。現在,你周圍添加通話try catch
塊打印機,使您的測試通過(同樣,你應該在你的應用程序做):
public bool TryPrint()
{
try
{
_printer.Print(_text);
return true;
}
catch (Exception ex)
{
// of course, log exception
return false;
}
}
當你在這裏做,你可以移動到Printer
創作。在你的情況下,它將是組件測試。好消息 - 你已經有了IPrinter
界面設計。所以,你寫的測試和驗證,在某些情況下,異常將被拋出:
[Test]
public void ShouldThrowExceptionWhenNoPaperLeft()
{
Printer printer = new Printer();
printer.PagesCount = 0;
Exception ex = Assert.Throws<Exception>(() => printer.Print("foo"));
Assert.That(ex.Message, Is.EqualTo("Out of paper"));
}
,當然還有,你寫你的組件實現通過該測試。之後,try catch
塊的課程將按預期工作,並且組件按預期工作,並在應有時引發異常。
不要抓。或者拋出異常。 – Zenwalker 2012-04-02 09:50:12
如果您的'Catch'塊沒有處理異常,那麼您的單元測試將無法通過拋出該特定異常,但如果抓住/處理了它,您的測試將通過。不確定是否有任何具體的解決方法。 – Rahul 2012-04-02 09:51:15
斷言異常,那麼測試用例不會失敗。 – Zenwalker 2012-04-02 09:59:34