2013-10-14 21 views
1

我想写一个测试检查,我的抽象类构造函数是否正确处理无效参数。我写了一个测试:NSububitute中的TargetInvocationException

[TestMethod] 
[ExpectedException(typeof(ArgumentException))] 
public void MyClassCtorTest() 
{ 
    var dummy = Substitute.For<MyClass>("invalid-parameter"); 
} 

这个测试没有通过,因为NSubstitute抛出一个TargetInvocationException而不是ArgumentException。我寻求的实际例外实际上是TargetInvocationExceptionInnerException。我可以写一个帮手方法,如:

internal static class Util { 

    public static void UnpackException(Action a) { 

     try { 

      a(); 
     } catch (TargetInvocationException e) { 

      throw e.InnerException; 
     } catch (Exception) { 

      throw new InvalidOperationException("Invalid exception was thrown!"); 
     } 
    } 
} 

但我想,那应该是某种解决这个问题的一般方法。有一个吗?

回答

2

NSubstitute目前没有解决此问题的一般方法。

其他一些解决方法包括手动继承抽象类来测试构造函数,或手动断言内部异常而不是使用ExpectedException

例如,假设我们有一个要求非负整数的抽象类:

public abstract class MyClass { 
    protected MyClass(int i) { 
     if (i < 0) { 
      throw new ArgumentOutOfRangeException("i", "Must be >= 0"); 
     } 
    } 
    // ... other members ... 
} 

我们可以在测试夹具创建一个子类测试的基类的构造函数:

[TestFixture] 
public class SampleFixture { 
    private class TestMyClass : MyClass { 
     public TestMyClass(int i) : base(i) { } 
     // ... stub/no-op implementations of any abstract members ... 
    } 

    [Test] 
    [ExpectedException(typeof(ArgumentOutOfRangeException))] 
    public void TestInvalidConstructorArgUsingSubclass() 
    { 
     new TestMyClass(-5); 
    } 
    // Aside: I think `Assert.Throws` is preferred over `ExpectedException` now. 
    // See http://stackoverflow.com/a/15043731/906 
} 

或者,您仍然可以使用模拟框架并对内部异常进行断言。我认为这是前一个选项不太可取,因为它不是显而易见的,为什么我们挖掘到TargetInvocationException,但这里有一个例子呢:

[Test] 
    public void TestInvalidConstructorArg() 
    { 
     var ex = Assert.Throws<TargetInvocationException>(() => Substitute.For<MyClass>(-5)); 

     Assert.That(ex.InnerException, Is.TypeOf(typeof(ArgumentOutOfRangeException))); 
    } 
+0

你怎么” ...手动断言内部异常上......“? –

+1

@hbob:我已经添加了两种方法的示例。如果您想了解更多信息,请告诉我。 –

+0

这些都是很好的例子,谢谢! –

相关问题