简体   繁体   English

Moq验证时间。一次不使用它。是特定参数

[英]Moq Verify Times.Once not working with It.Is specific parameter

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". 一次使用Search ==“垃圾”,一次使用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'. 我虽然在重要参数上使用It.Is,但应该给出正确的“ Once”。 Any ideas? 有任何想法吗?

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
{
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM