预期在模拟上调用一次,但被调用0次:没有配置任何设置?

时间:2018-10-30 18:05:22

标签: c# moq xunit

我使用Moq进行了以下xunit测试。

[Fact]
public void Presenter_Filter_ShouldFilterViewSearchList()
{
    var mockView = Mock.Get(mockSearchView);
    mockView.Setup(v => v.Ids).Returns("123");
    presenter.Filter();
    var mockRepo = Mock.Get(mockSearchRepository);
    Filter filter = new Filter { Ids = new List<string> { "123" } };
    mockRepo.Verify(r => r.GetSearchItems(5000, filter), Times.Once);
}

测试失败并显示以下消息。

Expected invocation on the mock once, but was 0 times: r => r.GetSearchItems(5000, Filter)
No setups configured.

Performed invocations: 
ISearchRepository.GetSearchItems(5000)
ISearchRepository.GetSearchItems(5000, Filter)

以下是经过测试的功能。而ISearchRepository.GetSearchItems(5000, Filter)被称为?

public void Filter()
{
    var filter = new Filter {
        Name = _view.Name,
        Ids = _view.Ids?.Split(',').Select(x => x.Trim()).ToList(),
        Countries = _view.Countries?.Split(',').Select(x => x.Trim()).ToList(),
        Region = _view.Region,
    };
    _repository.GetSearchItems(5000, filter);
}

1 个答案:

答案 0 :(得分:1)

您的函数正在创建自己的过滤器:

var filter = new Filter {
    Name = _view.Name,
    Ids = _view.Ids?.Split(',').Select(x => x.Trim()).ToList(),
    Countries = _view.Countries?.Split(',').Select(x => x.Trim()).ToList(),
    Region = _view.Region,
};

您正在使用其他过滤器实例设置测试:

Filter filter = new Filter { Ids = new List<string> { "123" } };
mockRepo.Verify(r => r.GetSearchItems(5000, filter), Times.Once);

如果要测试呼叫,则传递的对象必须是同一对象。

否则,将其配置为使用任何Filter对象进行呼叫:

 mockRepo.Verify(r => r.GetSearchItems(5000, It.IsAny<Filter>()), Times.Once);

或将过滤器作为参数传递给函数:

public void Filter(Filter filter) 
{
    _repository.GetSearchItems(5000, filter);
}