Reputation: 3290
I have an interface IMyInterface
that I am mocking in a unit test using moq.
Mock<IMyInterface> firstMockedObject = new Mock<IMyInterface>();
Mock<IMyInterface> secondMockedObject = new Mock<IMyInterface>();
The unit under test has a register method that looks like this:
public void RegisterHandler(Type type, IHandler handler)
and then a handle method:
public void Handle(IMyInterface objectToHandle)
What I am trying to test is that I can regiester 2 handlers for 2 different implementations of IMyInterface
and that the Handle method correctly selects which one to use:
UnitUnderTest.RegisterHAndler(firstMockedObject.Object.GetType(), handler1);
UnitUnderTest.RegisterHAndler(seconMockedObject.Object.GetType(), handler2);
The problem is both mocked objects are of the same type. Is there some way to force Moq to generate 2 mocks of the same interface as different types?
Upvotes: 6
Views: 2059
Reputation: 39015
Createtwo interfaces that derive from your interface. Use them for the mocks. The type of each one will be the mocked interface type:
public interface IMockOne : IMyInterface { };
public interface IMockTwo : IMyInterface { };
var firstMockedObject = new Mock<IMockOne>();
var secondMockedObject = new Mock<IMockTwo>();
This allows you to not implement a whole class for mocking, but to use moq
to create dynamic mocks.
Upvotes: 7
Reputation: 5488
You can create your own mock implementation for this test. Like
public class MockOne : IMyInterface {}
public class MockTwo : IMyInterface {}
Upvotes: 2