断言一个方法只被调用一次

Chr*_*age 28 tdd rhino-mocks mocking assertions

我想断言一个方法只被调用一次.我正在使用RhinoMocks 3.5.

这是我认为会起作用的:

[Test]
public void just_once()
{
    var key = "id_of_something";

    var source = MockRepository.GenerateStub<ISomeDataSource>();
    source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
        .Return(new Something())
        .Repeat.Once();

    var client = new Client(soure);

    // the first call I expect the client to use the source
    client.GetMeMyThing(key);

    // the second call the result should be cached
    // and source is not used
    client.GetMeMyThing(key);
}
Run Code Online (Sandbox Code Playgroud)

我想如果第二次调用测试失败GetMeMyThing()的呼叫source.GetSomethingThatTakesALotOfResources().

Jud*_*ngo 32

以下是我验证方法被调用一次的方法.

[Test]
public void just_once()
{
    // Arrange (Important to GenerateMock not GenerateStub)
    var a = MockRepository.GenerateMock<ISomeDataSource>();
    a.Expect(x => x.GetSomethingThatTakesALotOfResources()).Return(new Something()).Repeat.Once();

    // Act
    // First invocation should call GetSomethingThatTakesALotOfResources
    a.GetMeMyThing();

    // Second invocation should return cached result
    a.GetMeMyThing();

    // Assert
    a.VerifyAllExpectations();
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*ill 16

我一直在使用AssertWasCalled扩展来解决这个问题.这是我能找到/得到的最好的但如果我不必两次指定呼叫会更好.

    [Test]
    public void just_once()
    {
        var key = "id_of_something";

        var source = MockRepository.GenerateStub<ISomeDataSource>();

        // set a positive expectation
        source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
            .Return(new Something())
            .Repeat.Once();

        var client = new Client(soure);
        client.GetMeMyThing(key);
        client.GetMeMyThing(key);

        source.AssertWasCalled(x => x.GetSomethingThatTakesALotOfResources(key),
                               x => x.Repeat.Once());
        source.VerifyAllExpectations();
    }
Run Code Online (Sandbox Code Playgroud)


tva*_*son 5

你可能有兴趣在该位从犀牛嘲笑3.5文档(下面引用).看起来你需要模拟类,而不是存根,因为它可以按照你期望的方式工作.

存根和模拟之间的区别

...

模拟是一个我们可以设置期望的对象,它将验证预期的操作确实已经发生.存根是您用于传递给测试代码的对象.您可以设置它的期望,因此它会以某种方式起作用,但这些期望永远不会得到验证.存根的属性将自动表现为普通属性,您无法设置它们的期望.

如果要验证测试代码的行为,您将使用具有适当期望的模拟,并验证.如果您只想传递可能需要以某种方式执行的值,但不是此测试的焦点,则将使用存根.

重要信息:存根永远不会导致测试失败.