Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock same interface as 2 different types

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?

like image 230
pquest Avatar asked Nov 24 '15 15:11

pquest


2 Answers

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.

like image 144
JotaBe Avatar answered Nov 01 '22 13:11

JotaBe


You can create your own mock implementation for this test. Like

public class MockOne : IMyInterface {}
public class MockTwo : IMyInterface {}
like image 25
Valentin Avatar answered Nov 01 '22 12:11

Valentin