Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking the is operator in Moq

Tags:

c#

mocking

moq

Is there a way to get my mocks to impersonate a type? I am trying to do something like this:

var myMock = new Mock<IMyType>();
myMock.Setup(x => x.GetType()).Returns(typeof(MyTypeImpl));

however, GetType is not overrideable.

Any suggestions?

like image 550
Jeffrey Cameron Avatar asked Jun 09 '09 12:06

Jeffrey Cameron


2 Answers

Instead of using the is operator to check types, you could (not should) implement your own overridable interface method that performs a similar function, and implement it with the is operator (or typeof()/GetType()) on your usual bunch of classes.

That said, if you're using the is operator in a way that needs to be testable like this, it's more likely than not that you're basically defeating the purpose of polymorphism and interfaces somewhere along the line. I'd think about whether I could just get rid of it.

like image 195
mqp Avatar answered Nov 18 '22 09:11

mqp


I know this is an old post, but I was searching for a solution to this issue...

Using Moq it is possible to add the standard GetType signature to your interface, allowing Moq to mock the method, without the need for writing any more code as the method is already implemented for you.

Type GetType();
like image 20
Paul Avatar answered Nov 18 '22 08:11

Paul