1

我已经开始阅读“单元测试的艺术”,我正在尝试实现这段代码:

[Test]
public void ReturnResultsFromMock()
{
    MockRepository mocks = new MockRepository();
    IGetResults resultGetter = mocks.DynamicMock<IGetResults>();
    using(mocks.Record())
     {
        resultGetter.GetSomeNumber("a");//#1
        LastCall.Return(1);
        resultGetter.GetSomeNumber("a");//#2 how it should work?
        LastCall.Return(2);
        resultGetter.GetSomeNumber("b");
        LastCall.Return(3);
    }
    int result = resultGetter.GetSomeNumber("b");
    Assert.AreEqual(3, result);
    int result2 = resultGetter.GetSomeNumber("a");
    Assert.AreEqual(1, result2);
    int result3 = resultGetter.GetSomeNumber("a");
    Assert.AreEqual(2, result3);
}

运行测试 AOUT.Loga.Tests.LogAnalyzerTest.ReturnResultsFromMock 后收到此错误消息 :预期:2 但为:1

4

2 回答 2

2

看起来您尝试实现有序的调用序列(请参阅此处的详细信息):

  • 首先你调用GetSomeNumber("a")应该返回 1
  • 然后GetSomeNumber("a")再次调用,结果将是 2
  • 只有这样GetSomeNumber("b"),结果才会是 3

是这样,尝试替换using(mocks.Record())using(mocks.Ordered()). 但是,这只适用于这个调用序列

在您的示例中,您正在使用using(mocks.Record()),因此每次调用GetSomeNumber("a")都会根据您的配置返回 2 。你GetSomeNumber("a")被第二个覆盖。以下是正确的假设:

int result = resultGetter.GetSomeNumber("b");
Assert.AreEqual(3, result);
int result2 = resultGetter.GetSomeNumber("a");
Assert.AreEqual(2, result2); // every call to GetSomeNumber("a") will returns 2
int result3 = resultGetter.GetSomeNumber("a");
Assert.AreEqual(2, result3);
于 2012-06-15T11:18:26.423 回答
0

您可以尝试使用更简单的Rhino Mocks AAA 语法,您的代码将如下所示(也请查看此问题):

    // Arrange
    var resultGetter = MockRepository.GenerateMock<IGetResults>;
    resultGetter.Expect(x => x.GetSomeNumber("b")).Return(3);
    resultGetter.Expect(x => x.GetSomeNumber("a")).Return(1).Repeat.Once();
    resultGetter.Expect(x => x.GetSomeNumber("b")).Return(2).Repeat.Once();

    // Act
    int result = resultGetter.GetSomeNumber("b");
    // Assert
    Assert.AreEqual(3, result);
    // Act
    int result2 = resultGetter.GetSomeNumber("a");
    // Assert
    Assert.AreEqual(1, result2);
    // Act
    int result3 = resultGetter.GetSomeNumber("a");
    // Assert
    Assert.AreEqual(2, result3);
于 2012-06-19T07:37:46.600 回答