Programming  /  Testing September 17, 2009

Setting Expectations With StructureMap’s MoqAutoMocker

I’m playing around with StructureMap’s auto mocking functionality to make a few tests more maintainable. There are a few good examples on how to use auto mocking on StructureMap’s site which has been a great help. They do however show how to work with auto mocking when using Rhino Mocks and since I’m using Moq, where the syntax for setting and verifying expectations is a bit different, I got a bit confused.

The code for one of my tests look something like this:

public void GivenID_GetBlog_ReturnsBlogFromHandler()
    int id = 1;
    Blog expectedBlog = new Mock<Blog>().Object;
    MoqAutoMocker<MetaWeblogHandler> autoMetaWebLoghandler = new MoqAutoMocker<MetaWeblogHandler>();
    MetaWeblogHandler metaWeblogHandler = autoMetaWebLoghandler.ClassUnderTest;
    Blog returnedBlog = metaWeblogHandler.GetBlog(id.ToString());

    Assert.Equal<Blog>(expectedBlog, returnedBlog);

The above code verifies that the GetBlog method in MetaWebLogHandler returns an instance of Blog which it retrieves from the GetBlog method of an instance of IBlogHandlerFacade. The IBlogHandlerFacade is in turn a constructor parameter to MetaWebLogHandler and therefore MoqAutoMocker will automatically create a fake instance of it.

There’s a problem with the above test and it is that the fake instance if IBlogHandlerFacade doesn’t know what to return when it’s GetBlog method is called. When using Rhino Mocks the solution would be very straight forward, I would simply ask my MoqAutoMocker<MetaWeblogHandler> for the mock object of type IBlogHandlerFacade and set up the expectation on it, like this:

autoMetaWebLoghandler.Get<IBlogHandlerFacade>().Setup(handler => handler.GetBlog(id)).Returns(expectedBlog);

When using Mock though it seems I have to take a slightly different approach and instead do this:

Mock.Get(autoMetaWebLoghandler.Get<IBlogHandlerFacade>()).Setup(handler => handler.GetBlog(id)).Returns(expectedBlog);

That is, I must first retrieve the mock object from the MoqAutoMocker<MetaWeblogHandler> and then ask Mock (the class) for it’s corresponding Mock<IBlogHandlerFacade> on which I can then set up expectations on.

PS. For updates about new posts, sites I find useful and the occasional rant you can follow me on Twitter. You are also most welcome to subscribe to the RSS-feed.

Joel Abrahamsson

Joel Abrahamsson

I'm a passionate web developer and systems architect living in Stockholm, Sweden. I work as CTO for a large media site and enjoy developing with all technologies, especially .NET, Node.js, and ElasticSearch. Read more


comments powered by Disqus

More about Testing