问题描述
我很难理解如何在MockingKernel
内部生成的基础Mock<T>
上进行.SetupXXX()
调用.任何人都可以弄清楚它应该如何工作?
I'm having a really hard time trying to figure how I can do .SetupXXX()
calls on the underlying Mock<T>
that has been generated inside the MockingKernel
. Anyone who can shed some light on how it is supposed to work?
推荐答案
您需要在MoqMockingKernel
上调用GetMock<T>
方法,该方法将返回生成的Mock<T>
,您可以在其上调用.SetupXXX()/VerifyXXX()
方法.
You need to call the GetMock<T>
method on the MoqMockingKernel
which will return the generated Mock<T>
on which you can call your .SetupXXX()/VerifyXXX()
methods.
这是一个示例单元测试,演示了GetMock<T>
的用法:
Here is an example unit test which demonstrates the GetMock<T>
usage:
[Test]
public void Test()
{
var mockingKernel = new MoqMockingKernel();
var serviceMock = mockingKernel.GetMock<IService>();
serviceMock.Setup(m => m.GetGreetings()).Returns("World");
var sut = mockingKernel.Get<MyClass>();
Assert.AreEqual("Hello World", sut.SayHello());
}
涉及的类型如下:
public interface IService { string GetGreetings(); }
public class MyClass
{
private readonly IService service;
public MyClass(IService service) { this.service = service; }
public string SayHello()
{
return string.Format("Hello {0}", service.GetGreetings());
}
}
请注意,您可以使用MoqMockingKernel.MockRepository
属性访问生成的Moq.MockRepository
(如果您更喜欢SetupXXX方法,则可以使用它).
Note that you can access the generated Moq.MockRepository
(if you prefer it over the SetupXXX methods) with the MoqMockingKernel.MockRepository
property.
这篇关于如何使用Ninject的MockingKernel(moq)设置模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!