I have the following xunit test using Moq
.
[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);
}
And the test failed with the following messages.
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)
The following is the tested function. And ISearchRepository.GetSearchItems(5000, Filter)
is called?
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);
}
Your function is creating its own 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,
};
You are setting up a test with a different instance of the filter:
Filter filter = new Filter { Ids = new List<string> { "123" } };
mockRepo.Verify(r => r.GetSearchItems(5000, filter), Times.Once);
If you wish to test the call, the object passed must be the same object.
Otherwise, configure it to use any Filter
object for the call:
mockRepo.Verify(r => r.GetSearchItems(5000, It.IsAny<Filter>()), Times.Once);
Or pass the filter as an argument to the function:
public void Filter(Filter filter)
{
_repository.GetSearchItems(5000, filter);
}