I am using Rhino Mocks 3.6. I have seen many types of coding. Sometimes using static GenerateMock method, sometimes using new MockRepository(). I don’t understand pretty well what is happening or what is better. Maybe some methods are obsolete, but anyway, let’s go to the real issue.
I would like to understand better what is happening in the code below and what is really needed to have a better test.
[TestMethod]
public void TestingProperty()
{
Person repository = MockRepository.GenerateMock<Person>();
// tell rhino.mocks when FirstName is called in the next time, it should return "Monica"
repository.Expect(x => x.Title).Return("Monica");
// get the mocking ready
repository.Replay();
repository.VerifyAllExpectations();
// when getting repository.Title value, we should receive "Monica" defined previously in expectation
Assert.AreEqual(repository.Title, "Monica");
}
I noticed when I remove repository.Replay(), everything keeps on working. What is the purpose of Replay, is it needed?
VerifyAllExpectations is also needed? What is it doing internally?
Can I avoid typing manually “Monica” and have a real mock object for Person?
If this is a bad code please let me know your suggestions!
It sounds like you haven’t worked with more recent mock object frameworks.
In older “mock objects”, you have to do assertions manually against state of the mock object. For example, you’d run the code under test, which adds items to a list on your mock object. At the end of your test, you’d verify that the list on that mock object is populated correctly. This is verifying the state of the mock.
This older style is like a less sophisticated version of a Rhino stub.
With newer mock object frameworks, you stop verifying state of mock objects, and start verifying behavior. You make assertions about how your code under test calls your mock objects, not how properties/members are set.
You’ll still do your classical assertions on the code under test. But you won’t do classical assertions on your mocks. You’ll instead set up expectations, and verify them with Rhino assertions.
Some tips to correct this code:
VerifyAllExepectations, passing mocks to it as necessaryvirtualorabstract, or that your mock is based off aninterfaceHere’s some corrected example code:
To test that this is working correctly, try these things (change the code back after each one):
Expectline, run it, and make sure it still passes (this isn’t a strict mock)Expectline, returning a different value. Run it, and make sure it failsSomeMethodcall. Run it, and make sure it passes (not a strict mock)SomeMethod. Run it, and make sure it fails