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?
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.
You've not specified for the mock that it should store the value and return that value, so it's just returning the default value of a bool
. I'd say the reason for the difference in behaviour is because there is an implied difference between mocks and stubs in terms of usage, intent and behaviour.
Have a bit of a read-up on the differences between mocks, stubs and fakes. Not everyone agrees on a single answer, but you'll see there's a general consensus. Starting here might help: What's the difference between faking, mocking, and stubbing?
精彩评论