Moq Extension Methods for Unity

A few people have asked about the RegisterMock extension method used in another post. The usage looks like this:

[Test]
public void Should_delete_removed_image()
{
    container.RegisterMock<IFileRepository>()
        .Setup(r => r.Delete(It.IsAny<IFile>()))
        .Verifiable();

    container.RegisterMock<IBusinessRepository>()
        .Setup(r => r.FindById(3))
        .Returns(CreateBusinessWith(new BusinessImage { ImageId = 4 }));

    var controller = container.Resolve<BusinessGalleryController>();
    controller.Delete(3, 4);

    container.VerifyMockFor<IFileRepository>();
}

It’s just a few helper extensions for using Moq with Unity that cut down on the noise in tests. My friend Keith came up with it, I just happen to blog about it first. Here it is:

public static class MoqExtensions
{
    public static Mock<T> RegisterMock<T>(this IUnityContainer container) where T : class
    {
        var mock = new Mock<T>();

        container.RegisterInstance<Mock<T>>(mock);
        container.RegisterInstance<T>(mock.Object);

        return mock;
    }

    /// <summary>
    /// Use this to add additional setups for a mock that is already registered
    /// </summary>
    public static Mock<T> ConfigureMockFor<T>(this IUnityContainer container) where T : class
    {
        return container.Resolve<Mock<T>>();
    }

    public static void VerifyMockFor<T>(this IUnityContainer container) where T : class
    {
        container.Resolve<Mock<T>>().VerifyAll();
    }
}

5 Comments  »

  1. Paolo says:

    Thanks Michael! But I’ve got one more request…
    I’m using Rhino Mocks and I can’t port your code. Can you help me?
    Thanks.
    Paolo

  2. Michael Valenty says:

    I took a look at Rhino Mocks and I don’t think it is a good fit for these extension methods. It doesn’t use the same fluent style setup that Moq uses, so the extension methods won’t really be much help.

  3. Keith says:

    Good job Mike. I have been meaning to write about RegisterMock for awhile now…

  4. Stef says:

    Mike, nice code !

    I’ve added a new extension-method and updated RegisterMock method like this:

    public static void RegisterExistingMock(this IUnityContainer container, Mock mock) where T : class
    {
        container.RegisterInstance(mock);
        container.RegisterInstance(mock.Object);
    }
    
    // In this way it's possible to add a already existing mock to Unity like:
    
    var mock = new Mock();
    mock.Setup(s => s.GetUser("a")).Returns(new User() {UserId = 100, UserName = "a" });
    mock.Setup(s => s.GetUser("b")).Returns(new User() {UserId = 200, UserName = "b" });
    
    container.RegisterExistingMock(mock);
    

    I hope this makes sense.

    Grtz,
    Stef

  5. Michael Valenty says:

    Thanks Stef, I like the addition.

Trackbacks/Pingbacks

    1. Auto-Mocking Unity Container Extension | Agile at Work

    RSS feed for comments on this post, TrackBack URI

    Leave a Comment