2011-04-23 93 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)); 
    } 
} 
相关问题