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?
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.
You can create your own mock implementation for this test. Like
public class MockOne : IMyInterface {}
public class MockTwo : IMyInterface {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With