2014-02-19 67 views
0

我正在使用RhinoMocks,我想斷言一個屬性引用的Action沒有被調用,但我並不關心屬性本身。AssertWasNotCalled on Action屬性

實施例:

public class MyClass 
{ 
    public Action DoSomething { get; set; } 

    public void TryDoSomething() 
    { 
     if(DoSomething != null) 
      DoSomething(); 
    } 
} 

[TestMethod] 
public void TestDoSomethingNotCalled() 
{ 
    var myclass = new MockRepository.GeneratePartialMock<MyClass>(); 

    myclass.TryDoSomething(); 

    myclass.AssertWasNotCalled(m => m.DoSomething()); 
} 

該測試失敗,因爲上DoSomething的空校驗的。有沒有辦法斷言這個屬性引用的Action沒有被調用,而不是屬性本身?

回答

-1

看着MyClass.TryDoSomething()代碼,我認爲有2例下進行試驗:

  1. DoSomething爲空:然後你只需要當調用TryDoSomething()時,檢查沒有NullReferenceException。無需驗證DoSomething操作是否被調用,因爲沒有任何要調用的操作。
  2. DoSomething不爲空:然後您需要檢查在調用TryDoSomething()時調用DoSomething。你自己的答案顯示了一個很好的例子。但是您需要將Assert.IsFalse()更改爲Assert.IsTrue()
+0

我跳過槍,沒有看到您的完整回覆。我試圖提出這個問題,但它不會讓我。謝謝! – ConditionRacer

0

最後我做了以下內容:

[TestMethod] 
public void TestDoSomethingCalled() 
{ 
    var myclass = new MyClass(); 

    bool methodcalled = false; 
    myclass.DoSomething =() => { methodcalled = true; }; 

    myclass.TryDoSomething(); 

    Assert.IsTrue(methodcalled); 
} 

[TestMethod] 
public void TestDoSomethingNotCalled() 
{ 
    var myclass = new MyClass(); 

    AssertDoesNotThrow<NullReferenceException>(
     () => { myclass.TryDoSomething(); }); 
} 
+0

該測試失敗。你有沒有試過針對這個問題的代碼運行這個測試? –

+0

更新爲反映您的答案 – ConditionRacer