How to do Setup of mocks with Ninject's MockingKernel (moq)

五迷三道 提交于 2020-01-03 07:38:09

问题


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?


回答1:


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.

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

Where the involved types are the following:

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

Note that you can access the generated Moq.MockRepository (if you prefer it over the SetupXXX methods) with the MoqMockingKernel.MockRepository property.



来源:https://stackoverflow.com/questions/13212655/how-to-do-setup-of-mocks-with-ninjects-mockingkernel-moq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!