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(); } }
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
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.
Good job Mike. I have been meaning to write about RegisterMock for awhile now…
Mike, nice code !
I’ve added a new extension-method and updated RegisterMock method like this:
I hope this makes sense.
Grtz,
Stef
Thanks Stef, I like the addition.
That’s exactly what I need. Thank you