Reputation: 585
I have a mock setup:
_mock.Setup( x => x.Method( It.IsAny<Model>(), It.IsAny<string>(), IsAny<int>()));
and verify with:
_mock.Verify(x => x.Method( It.Is<Model>( p=> p.IsPresent && p.Search.Equals("term")), It.IsAny<string>(), It.IsAny<int>()), Times.Once());
public Results GetResults( Model model, string s, int i)
{
return _repo.Method(model, s, i);
}
During test the method is called twice. Once with Search == "rubbish" and once with Search=="term". Yet verify fails with the message it's being invoked 2 times.
I though using It.Is on the important parameter should give the correct 'Once'. Any ideas?
Upvotes: 1
Views: 4195
Reputation: 1720
Just tried to restore you case and get working example. Please take a look, may be it helps you to solve the issue:
[Test]
public void MoqCallTests()
{
// Arrange
var _mock = new Mock<IRepo>();
// you setup call
_mock.Setup(x => x.Method(It.IsAny<Model>(), It.IsAny<string>(), It.IsAny<int>()));
var service = new Service(_mock.Object);
// Act
// call method with 'rubbish'
service.GetResults(new Model {IsPresent = true, Search = "rubbish"}, string.Empty, 0);
// call method with 'term'
service.GetResults(new Model {IsPresent = true, Search = "term" }, string.Empty, 0);
// Assert
// your varify call
_mock.Verify(x => x.Method(It.Is<Model>(p => p.IsPresent && p.Search.Equals("term")), It.IsAny<string>(), It.IsAny<int>()), Times.Once());
}
public class Service
{
private readonly IRepo _repo;
public Service(IRepo repo)
{
_repo = repo;
}
// your method for tests
public Results GetResults(Model model, string s, int i)
{
return _repo.Method(model, s, i);
}
}
public interface IRepo
{
Results Method(Model model, string s, int i);
}
public class Model
{
public bool IsPresent { get; set; }
public string Search { get; set; }
}
public class Results
{
}
Upvotes: 1