2013-01-02 42 views
8

我想創建一個方法,該方法需要一個testdelegate或委託並將參數傳遞給委託對象。這是因爲我正在爲控制器中的一個方法創建一個測試,它們都採用相同的參數(一個id),並且我不想爲所有控制器方法創建一個測試。將參數傳遞給NUnit中的TestDelegate

代碼,我有:

protected void AssertThrows_NullReference_Og_InvalidOperation(TestDelegate delegateMethod) 
{ 

    Assert.Throws<NullReferenceException>(delegateMethod); 
    Assert.Throws<InvalidOperationException>(delegateMethod); 
    Assert.Throws<InvalidOperationException>(delegateMethod); 
} 

我想怎麼辦:

protected void AssertThrows_NullReference_Og_InvalidOperation(TestDelegate delegateMethod) 
{ 

    Assert.Throws<NullReferenceException>(delegateMethod(null)); 
    Assert.Throws<InvalidOperationException>(delegateMethod(string.Empty)); 
    Assert.Throws<InvalidOperationException>(delegateMethod(" ")); 
} 

編輯: 我忘了提,該控制器具有一個返回值。因此Action不能使用。

+0

看到我的更新答案 –

+1

你是對的。我在底部添加了我自己的解決方案,我借用了你的代碼並做了一些調整。謝謝你的幫助。 –

回答

10

使用Action<string>來傳遞接受單個字符串參數的方法。調用該動作與您的測試參數:

protected void AssertThrowsNullReferenceOrInvalidOperation(Action<string> action) 
{ 
    Assert.Throws<NullReferenceException>(() => action(null)); 
    Assert.Throws<InvalidOperationException>(() => action(String.Empty)); 
    Assert.Throws<InvalidOperationException>(() => action(" ")); 
} 

用法:

[Test] 
public void Test1() 
{ 
    var controller = new FooController(); 
    AssertThrowsNullReferenceOrInvalidOperation(controller.ActionName); 
} 

UPDATE:

使用Func<string, ActionResult>的控制器返回的ActionResult。您也可以爲此創建通用方法。

1

正如在編輯中所說的,控制器具有返回類型。因此,我不得不從Action更改爲Func,因爲我在單元測試中使用它,所以我不得不創建一個臨時對象來保存函數。

基於lazyberezovsky的答案這裏是我的最終代碼:

public class BaseClass 
    { 
      protected Func<string, ActionResult> tempFunction; 
      public virtual void AssertThrowsNullReferenceOrInvalidOperation() 
      { 
       if (tempFunction != null) 
       { 
        Assert.Throws<NullReferenceException>(() => tempFunction(null)); 
        Assert.Throws<InvalidOperationException>(() => tempFunction(string.Empty)); 
        Assert.Throws<InvalidOperationException>(() => tempFunction(" ")); 
       } 
      } 
    } 

單元測試則是:

[TestFixture] 
public class TestClass 
{ 
     [Test] 
     public override void AssertThrowsNullReferenceOrInvalidOperation() 
     { 
      tempFunction = Controller.TestMethod; 
      base.AssertThrowsNullReferenceOrInvalidOperation(); 
     } 
}