2011-04-23 96 views
3

我想獲得以下代碼的一些單元測試覆蓋率:如何用內部異常對代碼進行單元測試?

public static class ExceptionExtensions { 
    public static IEnumerable<Exception> SelfAndAllInnerExceptions(
     this Exception e) { 
     yield return e; 
     while (e.InnerException != null) { 
     e = e.InnerException; //5 
     yield return e; //6 
     } 
    } 
} 

編輯:看來我沒必要痣來測試該代碼。另外,我有一個錯誤,第5行和第6行反轉。

+2

爲什麼需要痣來測試?功能看起來可以用傳統的單元測試技術進行測試。 – 2011-04-23 13:21:25

回答

3

這是我得到了(沒必要痣畢竟):

[TestFixture] 
public class GivenException 
{ 
    Exception _innerException, _outerException; 

    [SetUp] 
    public void Setup() 
    { 
     _innerException = new Exception("inner"); 
     _outerException = new Exception("outer", _innerException); 
    } 

    [Test] 
    public void WhenNoInnerExceptions() 
    { 
     Assert.That(_innerException.SelfAndAllInnerExceptions().Count(), Is.EqualTo(1)); 
    } 

    [Test] 
    public void WhenOneInnerException() 
    { 
     Assert.That(_outerException.SelfAndAllInnerExceptions().Count(), Is.EqualTo(2)); 
    } 

    [Test] 
    public void WhenOneInnerException_CheckComposition() 
    { 
     var exceptions = _outerException.SelfAndAllInnerExceptions().ToList(); 
     Assert.That(exceptions[0].InnerException.Message, Is.EqualTo(exceptions[1].Message)); 
    } 
} 
相關問題