![](/img/trans.png)
[英]Using Moq `It.Is` to verify constructor parameter / object with private field
[英]Moq Verify Times.Once not working with It.Is specific parameter
我有一个模拟设置:
_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”。 有任何想法吗?
只是尝试恢复您的情况并获得有效的示例。 请看一下,也许可以帮助您解决问题:
[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
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.