简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM