![](/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.