我有一个模拟设置:
_mock.Setup( x => x.Method( It.IsAny<Model>(), It.IsAny<string>(), IsAny<int>()));
并通过以下方式进行验证:
_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);
}
在测试过程中,该方法被调用了两次。一次使用Search ==“垃圾”,一次使用Search ==“ term”。然而,验证失败并显示消息已被调用两次。
我虽然使用It.Is在重要参数上,但应该给出正确的“ Once”。有什么想法吗?
答案 0 :(得分:0)
请尝试恢复您的情况并获得有效的示例。请看一下,也许可以帮助您解决问题:
[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
{
}