代码之家  ›  专栏  ›  技术社区  ›  Gabe Moothart

验证使用Moq调用受保护方法的次数

  •  12
  • Gabe Moothart  · 技术社区  · 15 年前

    在我的单元测试中,我使用Moq模拟了一个受保护的方法,并断言它被调用了一定次数。 This question

    //expect that ChildMethod1() will be called once. (it's protected)
    testBaseMock.Protected().Expect("ChildMethod1")
      .AtMostOnce()
      .Verifiable();
    
    ...
    testBase.Verify();
    

    但是这已经不起作用了;从那以后语法已经改变了,我无法使用Moq 4.x找到新的等价物:

    testBaseMock.Protected().Setup("ChildMethod1")
      // no AtMostOnce() or related method anymore
      .Verifiable();
    
    ...
    testBase.Verify();
    
    2 回复  |  直到 9 年前
        1
  •  26
  •   Malice    11 年前

    Moq.Protected 命名空间,有一个 IProtectedMock 具有以时间为参数的验证方法的接口。

    编辑 这是因为最低起订量4.0.10827。语法示例:

    testBaseMock.Protected().Setup("ChildMethod1");
    
    ...
    testBaseMock.Protected().Verify("ChildMethod1", Times.Once());
    
        2
  •  15
  •   Shaun Luttin    9 年前

    为了补充绪方的答案,我们还可以 验证接受参数的受保护方法 :

    testBaseMock.Protected().Setup(
        "ChildMethod1",
        ItExpr.IsAny<string>(),
        ItExpr.IsAny<string>());
    
    testBaseMock.Protected().Verify(
        "ChildMethod1", 
        Times.Once(),
        ItExpr.IsAny<string>()
        ItExpr.IsAny<string>());
    

    ChildMethod1(string x, string y) .

    另请参见: http://www.nudoq.org/#!/Packages/Moq.Testeroids/Moq/IProtectedMock(TMock)/M/Verify

    推荐文章