Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using Moq to mock an interface, what happens to the methods?

Tags:

c#

testing

moq

When using Moq to mock an interface, what happens to the methods?

Let's say I have an interace ISomething, which IoC maps to the class Something. Then in my test I do this: var something = new Mock<ISomething>();.

Lets say the interface contains a method: string method();.

Now, if I call that method on the mocked instance, something.method(), will it be mapped to the class Something's implementation, or will it just return void? Will Moq try to map an interface with an implementation?

like image 853
ptf Avatar asked Sep 02 '25 01:09

ptf


1 Answers

Moq won't try to use your implemenation and it in fact doesn't know anything about it (even doesn't care if it exists). Instead it generates it's own class in runtime, which implements your interface ISomething. And it's implementation is what you configure it to be with something.Setup() methods.

If you skip configuring it, it will just return default value and do nothing else. For example,

var something = new Mock<ISomething>();
var result = something.Object.method(); // returns NULL

var somethingElse = new Mock<ISomething>();
somethingElse.Setup(s=>s.method()).Returns("Hello World");
var otherResult = somethingElse.Object.method(); // Returns "Hello World"

Setups can be quite complex, if you need that, including returning different results for different arguments, or for different calls (first time return one value, for second call - another). For more details you can check documentation.

Please note that something.Object and somethingElse.Object are completely different implementations (classes) of ISomething interface. You can check that by calling:

var whatMySomethingIs = something.Object.GetType();
var whatMySomethingElseIs = somethingElse.Object.GetType();
like image 50
Sasha Avatar answered Sep 04 '25 16:09

Sasha