单元测试,Rhino,单元测试的艺术

时间:2012-06-15 10:10:31

标签: unit-testing testing mocking rhino-mocks rhino

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

[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

2 个答案:

答案 0 :(得分:2)

您似乎尝试实施有序调用序列(请参阅详情here):

  • 首先,您致电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);

答案 1 :(得分:0)

你可以尝试使用更简单的Rhino Mocks AAA syntax,你的代码看起来像这样(看看this question):

    // 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);