简体   繁体   English

使用Moq模拟接口时,方法会发生什么?

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

When using Moq to mock an interface, what happens to the methods? 使用Moq模拟接口时,方法会发生什么?

Let's say I have an interace ISomething , which IoC maps to the class Something . 假设我有一个接口ISomething ,该接口IoC映射到类Something Then in my test I do this: var something = new Mock<ISomething>(); 然后在我的测试中,我这样做: var something = new Mock<ISomething>(); .

Lets say the interface contains a method: string 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? 现在,如果我在模拟实例上调用该方法something.method() ,它将被映射到Something类的实现,还是只是返回void? Will Moq try to map an interface with an implementation? Moq是否会尝试将接口与实现映射?

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). Moq不会尝试使用您的实现,而实际上它对此一无所知 (即使不在乎它是否存在)。 Instead it generates it's own class in runtime , which implements your interface ISomething . 相反,它在运行时生成自己的类,该类实现您的接口ISomething And it's implementation is what you configure it to be with something.Setup() methods. 而它的实现就是您将它配置为使用something.Setup()方法。

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. 请注意, something.ObjectsomethingElse.ObjectISomething接口的完全不同的实现(类)。 You can check that by calling: 您可以通过以下方式进行检查:

var whatMySomethingIs = something.Object.GetType();
var whatMySomethingElseIs = somethingElse.Object.GetType();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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