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?
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.
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();
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