我有点难以理解新的 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。这是一个理想的情况。当然,您可以同时拥有 Stub
和 AssertWasCalled
。
还有 Expect
和 VerifyAllExpectations
,它们的行为实际上与旧语法类似。我只会在同一测试中需要 Stub
和 AssertWasCalled
时使用它们,并且您有复杂的参数约束你不想写两次。通常,避免 Expect
和 VerifyAllExpectations
关于c# - Rhino Mocks 的新语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1520010/