c# - Rhino Mocks 的新语法

标签 c# .net unit-testing rhino-mocks

我有点难以理解新的 AAA 语法在 Rhino Mocks 中的工作原理。我的大多数测试如下所示:

    [Test]
    public void Test()
    {
        //Setup
        ISth sth= mocks.DynamicMock<ISth>();

        //Expectations
        Expect.Call(sth.A()).Return("sth");

        mocks.ReplayAll();
        //Execution
        FunctionBeingTested(sth);
        //...asserts, etc

        //Verification
        mocks.VerifyAll();
    }

使用 AAA 语法会是什么样子?

最佳答案

最有可能是这样的:

[Test]
public void Test()
{
    // Arrange
    ISth sth= MockRepository.GenerateMock<ISth>();

    sth
      .Stub(x => x.A())
      .Return("sth");

    // Act
    FunctionBeingTested(sth);

    // Assert
}

要真正受益于新的 AAA 语法,您必须稍微改变一下想法。我试着解释一下。

我的提案有一个主要区别:没有“Expect-Verify”。所以我建议不要期待这个调用,因为有返回值。我假设该方法在没有调用 sth.A 时无法通过测试,因为它会错过正确的返回值。它将至少使其他断言之一失败。

这实际上是一件好事。

  • 您可以将 stub 移动到 TestInitialize,当测试中未调用 stub 方法时(这不是期望),它不会造成伤害。您的测试将会变得更短。
  • 您的测试不知道被测系统“如何”完成工作,您只检查结果。您的测试将变得更易于维护。

还有另一种情况,您实际上需要检查模拟上是否调用了方法。主要是如果它返回 void。例如:应该触发事件、提交事务等等。为此,请使用 AssertWasCalled:

[Test]
public void Test()
{
    // Arrange
    ISth sth= MockRepository.GenerateMock<ISth>();

    // Act
    FunctionBeingTested(sth);

    // Assert
    sth
      .AssertWasCalled(x => x.A());
}

注意:没有返回值,因此没有Stub。这是一个理想的情况。当然,您可以同时拥有 StubAssertWasCalled


还有 ExpectVerifyAllExpectations,它们的行为实际上与旧语法类似。我只会在同一测试中需要 StubAssertWasCalled 时使用它们,并且您有复杂的参数约束你不想写两次。通常,避免 ExpectVerifyAllExpectations

关于c# - Rhino Mocks 的新语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1520010/

相关文章:

.net - 获取 WPF 视觉到 DirectX 纹理的快速代码(性能方面)

java - Maven 不运行 Spock 测试

c# - "x is null"和 "x == null"有什么区别?

c# - 如何强制使用 .Include 查询 Entity Framework 6 进行外部连接

c# - 使用 asp.net(C#) 更改 div 标签中的 css 类

c# - 在使用 WinAppDriver 单击之前等待元素

c# - 每个线程的处理时间?

unit-testing - Hamcrest和ScalaTest

javascript - 尝试模拟对象实例时,Sinon stub 不起作用

javascript - 使用 WebDriver 扩展 JavaScript 菜单