【问题标题】:Moq Verify Times.Once not working with It.Is specific parameterMoq 验证 Times.Once 不使用 It.Is 特定参数
【发布时间】:2018-09-27 09:15:19
【问题描述】:

我有一个模拟设置:

_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 == "rubbish",一次使用 Search=="term"。然而验证失败,消息被调用了 2 次。

我虽然在重要参数上使用 It.Is 应该给出正确的“Once”。有什么想法吗?

【问题讨论】:

  • 特定参数的验证看起来没问题,但是设置和验证中的参数数量不匹配 - 这是问题还是错字?
  • 感谢 Lennart,错字。现已修复。
  • @Craig 你能展示被测方法吗?
  • 上面添加的方法
  • Setup 行是多余的,可以删除。 Verify 的错误告诉您,该模拟上的方法没有使用所描述的参数调用。但正如 Nkosi 所说,如果没有 MCVE,那将是猜测。使用 MCVE 会更容易诊断。

标签: c# .net unit-testing moq


【解决方案1】:

刚刚尝试恢复您的案例并获得工作示例。请看一下,也许它可以帮助您解决问题:

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

【讨论】:

  • 谢谢,我创建了一个类似的缩减测试工具,它按预期工作。显然,在我的实际设置中发生了一些导致问题的事情。我会继续追踪。
  • @Craig 我遇到了类似的问题,并注意到如果传入的复杂对象发生变化,则验证调用似乎正在使用对象的该状态,而不是传递的对象进入方法。在我的情况下,我正在调用一个函数,更改对象,然后再次调用该函数,但“时间”检查无法区分。
猜你喜欢
  • 2011-06-24
  • 2021-01-11
  • 2013-02-28
  • 2012-11-09
  • 2013-04-06
  • 2010-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多