Kash Farooq's software development blog

.NET Developer

Posts Tagged ‘OO’

Recursive Mocks: Comparing Moq to Rhino Mocks

Posted by Kash Farooq on July 28, 2009

Here is the simple ASP.NET MVC code I want to test.
In a test, I need to mock the HttpContext so that it returns an identity that I control.

public ContentResult ReturnUserName() {
   return Content(User.Identity.Name);
}

And here is the test code using the released binaries of Rhino Mocks 3.5:

[Test]
public void ContentContainingUserNameReturned_RhinoMock() {
   var mockContext = MockRepository.GenerateStub<ControllerContext>();
   var mockHttpContext = MockRepository.GenerateStub<HttpContextBase>();
   mockContext.HttpContext = mockHttpContext;
   var identity = new GenericIdentity("user");
   mockHttpContext.User = new GenericPrincipal(identity,null);

   var controller = new HomeController {ControllerContext = mockContext};
   ContentResult content = controller.ReturnUserName();

   Assert.That(content.Content, Is.EqualTo("user"));
}

That’s a fair amount of mocking to test a one line method.

Here is the test using Moq:

[Test]
public void ContentContainingUserNameReturned_Moq() {
   var mockContext = new Mock<ControllerContext>();
   mockContext
     .SetupGet(x => x.HttpContext.User.Identity.Name)
     .Returns("user");

   var controller = new HomeController {ControllerContext = mockContext.Object};
   ContentResult content = controller.ReturnUserName();

   Assert.That(content.Content, Is.EqualTo("user"));
}

Far more concise.

The feature that allows Moq to do this is called Recursive Mocks.
You could argue that if you need to do this in your code then you must be breaking the Law Of Demeter. Sometimes, as with HttpContext, you don’t have a choice. Ayende argues you are breaking this law, but has introduced Recursive Mocking in Rhino Mocks, along with guidance. You’ll have to download the code and build you own binaries to use it though.

Advertisements

Posted in Moq, Rhino Mocks, Test Driven Development | Tagged: , , , , | Leave a Comment »