我使用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);
}
答案 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);
}