Search code examples
c#.netunit-testingrhino-mocks

Do I need to explicitly set expected return values on Mock object only?


Is my observation correct:

public intercafe IMyInterface { bool IsOK {get;set;} }

// If I use stub this always return true:
var stub = MockRepository.GenerateStub<IMyInterface>();
stub.IsOK = true;

// But if I use MOCK this always return false -NOT True
var mock= MockRepository.GenerateMock<IMyInterface>();
mock.IsOK = true;

If I am right; why is the reason?


Solution

  • The short answer is that you can set mock.IsOK to return true by setting an expectation on it and providing a return value:

    var mock= MockRepository.GenerateMock<IMyInterface>();
    mock.Expect(x => x.IsOK).Return(true);
    

    Of course, to understand why, it helps to understand the difference between mocks and stubs. Martin Fowler does a better job in this article than I could.

    Basically, a stub is intended to be used to provide dummy values, and in that sense Rhino.Mocks allows you to very easily arrange what you want those dummy values to be:

    stub.IsOK = true;
    

    Mocks, on the other hand, are intended to help you test behavior by allowing you to set expectation on a method. In this case Rhino.Mocks allows you to arrange your expectations using the following syntax:

    mock.Expect(x => x.IsOK).Return(true);
    

    Because a Mock and a Stub serve two different purposes they have entirely different implementations.

    In the case of your Mock example:

    var mock= MockRepository.GenerateMock<IMyInterface>();
    mock.IsOK = true;
    

    I wouldn't be surprised if the implementation of the IsOK setter on your mock is empty or ignoring your call completely.