2013-10-14 25 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

這些都是很好的例子,謝謝! –

相關問題