Problem with matching setup in Moq

非 Y 不嫁゛ 提交于 2019-12-14 02:20:18

问题


I've been using Moq for the past week or so and haven't had any issues until today. I'm having a problem with getting VerifyAll() to properly match the setup of my mock.

I'm currently writing unit tests for my application's API. Here's how the application is structured:

API <==> Service <==> DAO <==> Database

With this in mind, I'm mocking the service object and then constructing an API object using the mocked service. I've written a number of unit tests already without problem up until now.

I have two instance variables like this:

private Api _api;
private Mock<IHibernateService> mockService;

I initialize these in a setup method:

[SetUp]
public void DoSetupTasks()
{
    mockService = new Mock<IHibernateService>();
    _api = new Api(mockService.Object);
}

Here is the unit test that is failing:

    [Test]
    public void TestSearchOnAllProperties()
    {
        mockService
            .Setup(service => service.LoadAll(It.IsAny<Type>()))
            .Returns(new DomainBase[0]);

        var dmbs = _api.SearchOnAllProperties("search term", typeof(DomainBase));

        mockService.VerifyAll();
    }

The API's SearchOnAllProperties() method will subsequently make a call to the service's LoadAll() method (with some additional logic of course), so I want to verify that it's being called properly. To clarify, here's how LoadAll() is being called in SearchOnAllProperties():

public IEnumerable<DomainBase> SearchOnAllProperties(string searchTerm, Type type)
{
    foreach (DomainBase dmb in _hibernateService.LoadAll(type))
    {
        // additional logic
    }
}

However, when I run the unit test, I get a MockVerificationException stating that the given setup was not matched. I cannot figure out why as it should be calling the service's LoadAll() method.


回答1:


One possible cause is that at some point before this particular test method is called, mockService is being assigned to a new instance of Mock<IHibernateService>. If that is the case, then this test method would be calling Setup on the wrong instance, which would then produce this exception.

A quick way to test this would be to use local mockService and api variables and see if the test still fails:

[Test]
public void TestSearchOnAllProperties()
{
    var localMockService = new Mock<IHibernateService>();
    var localApi = new Api(localMockService.Object);

    localMockService
        .Setup(service => service.LoadAll(It.IsAny<Type>()))
        .Returns(new DomainBase[0]);

    var dmbs = localApi.SearchOnAllProperties("search term", typeof(DomainBase));

    localMockService.VerifyAll();
}

HTH



来源:https://stackoverflow.com/questions/4432682/problem-with-matching-setup-in-moq

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