views:

198

answers:

1

Using RhinoMocks, I have a catch-22 situation: I want to verify that a method is called, but this method needs to have an object returned on it because the returned object is acted on in the next line. In other words, mocking on the interface just returns a null value, but not mocking it up doesn't give me any way to verify that the method was called apart from some kind of integration test.

Therefore, looking at the contrived sample below that I threw together, is there a way to do what I'm wanting? I thought there might be a way to set the AssertWasCalled method to actually return something as when stubbing a method, but...thanks for any pointers (especially if it's simply a design flaw that should be addressed instead).

public class SomeClass
{
    private readonly ISomeMapper _someMapper;
    [Inject]
    public Test(ISomeMapper someMapper)
    {
        _someMapper = someMapper;
    }

    public SomeReturnType SomeMethod(IEnumerable<ISomethingToMap> somethings)
    {
        //foreach over somethings and do something based on various properties for each

        MappedSomething mappedSomething = _someMapper.Map(something); // AssertWasCalled here
        mappedSomething.SomeProperty = somethingFromSomewhere; // Which gets a null reference exception here (understandably) if _someMapper is mocked
        //end foreach after more stuff
    }

}

  ///...
    [Test]
    public void the_mapper_should_be_called()
    {
        //If mock or stub, then can AssertWasCalled, but then only null object returned.
        // If don't mock, then cannot assert whether was called.
        var mapper = MockRepository.GenerateStub<ISomeMapper>();

        var somethingToMap = _someListOfSomethings[0];

        var sut = new SomeClass(mapper);

        sut.SomeMethod(_someListOfSomethings);

        mapper.AssertWasCalled(x => x.Map(somethingToMap));
    }
+2  A: 

You can set an expectation on the mock object that the method was called along with the return value:

MappedSomething fakeMappedSomething = //whatever
mapper.Expect(m => m.Map(something)).Return(fakeMappedSomething);
...
sut.SomeMethod(_someListOfSomethings);

Then verify the expectations at the end of the test.

Lee
As usual it seems, it's the obvious first solution that I tried but failed to accurately implement in some way. Tried it yet again, and we're gold. Thanks!
Ted