Using Rhino Mocks to test objects
Yesterday Phil Haack posted up this nice post about how to code the MVP pattern in a web application. The implementation would look fairly familiar to anyone who has used MVC before but apparently big 'A' guy Martin Fowler asserts that there are now many different flavors of a model-view-controller|presenter pattern and in this post, Phil is showing us what the Supervising Controller pattern looks like.
One of the best things that I learned most from Phil's post was how he used the Rhino.Mocks library to create mock objects for his unit tests of his code. This looks like a very simple way to test code that is normally difficult to test - such as ASP.NET code or code whose state is heavily reliant upon certain runtime conditions to be met. In such cases you'll often find yourself factoring code out into interfaces and then writing testable stubs for them. Mock objects save you from writing lots of additional code just for the sake of getting testable stubs of objects. Here's some code from Phil's sample project in his post where he tests the events and the state of a view in his test code:
public void HandlesLoadEventAndSetsViewPropertiesCorrectly()
//Setup the service return values.
BlogPost blogPost = new BlogPost(1);
blogPost.Description = "My computer's cup holder is broken.";
//Setup the load event
viewMock.Load += null; //ugly syntax, I know, but the only way to get this to work
IEventRaiser loadRaiser = LastCall.IgnoreArguments().GetEventRaiser();
// Make sure that the proper service methods were called
// by the presenter.
//Now run the test.
new PostEditController(viewMock, this.dataServiceMock);
//Check that the view was properly populated.
Assert.AreEqual("My computer's cup holder is broken.", viewMock.BlogPostBody);
If the code looks a little odd then read from one of Phil's other fine article where he specifically shows how to use Rhino.Mocks to test events - that will help explain what some of that code is doing.
8/11/2006 5:48:52 AM
Some aspects of ASP.NET are still hard to test with RhinoMocks because many classes are sealed. RhinoMocks can't mocked sealed classes.
That's why I still use this old technique.http://haacked.com/archive/2005/06/11/4617.aspx