Rhino Mocks expectations

One of the most powerful tools you can use with Rhino Mocks is its “Expect” tool. So that instead of setting what should be returned when calling a method/property on a stub/mock object, you can set that you expect that to be called and what should it return, useful in different ways:

SetupResult.For(User.Name).Return("Ruben"); // This works when setting up the object.
User.Expect(x => x.Name).Return("Ruben"); // This is setting an expectation
User.Stub(x => x.Name).Return("Ruben"); // Yes, Rhino Mocks is so flexible.

Each one of those ways of setting a return value will have its uses and limitations, but I’m going to focus on the Expect() on this post. The expect as it is there will return that value just once, so that if you call “User.Name” more than once the second one will return an InvalidCallException (or NullReference, can’t remember now). To avoid that you could do something like this:

User.Expect(x => x.Name).Return("Ruben").Repeat.Any();

The reason for that has to do with expectations not being the standard way of configuring what an object returns, their main purpose is to know if something was requested and, even more, how was it requested. You could add more that one expectation in order to make it return “Ruben” the first time it’s called and “Peter” the second one, making it much more flexible.

Let’s imagine you want to test a unit and to make sure that the unit will do its work you need to check if something was saved/modified. You could access some database to check the results or you can set and expectation to check if the method calls that db.Save() method and, even more, what values are being sent on that method. So imagine that we send a User with name “Peter” but we expect the method to clean that and rewrite it to Ruben and then save to the db, we could set an expectation to check if db.Save was called and the user name was Ruben:

-

To assert that the expectation was met you just need to call some verifier or use a Mock Object, the difference between stubs and mock objects here is that a stub won’t check the expectations unless you tell it to do so, while mock objects will allways verify their expectations to pass the test.

User.VerifyAllExpectations();

Have in mind that when unit testing the goal is never to check if a method calls that other or not, as you would be testing the implementation instead than the behaviour, this trick is just a way of checking if the method did it’s work, which is not callign a db.Save, but to rename the username to “Ruben”. That’s what we are testing, and the way to check that can vary but the goal can’t, never forget that.

Close Bitnami banner
Bitnami