Question

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?

Was it helpful?

Solution 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().

OTHER TIPS

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(); });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top