문제

I'm using RhinoMocks and I'd like to assert that an Action that a property refers to is not called, but I don't care about the property itself.

Example:

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());
}

This test fails because of the null check on DoSomething. Is there a way to assert that the Action this property refers to is not called, and not the property itself?

도움이 되었습니까?

해결책 2

Looking at MyClass.TryDoSomething() code I think there are 2 cases which should be tested:

  1. DoSomething is null: Then you just need to check there is no NullReferenceException when TryDoSomething() is called. No need to verify whether DoSomething Action is called as there is nothing to call.
  2. DoSomething is not null: Then you need to check that DoSomething is called when TryDoSomething() is called. Your own answer shows a good example how to do this. But of cource you need to Change Assert.IsFalse() to Assert.IsTrue().

다른 팁

I ended up doing the following:

[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(); });
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top