简体   繁体   中英

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". 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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