Rhino Mocks - 通过多次调用模拟其返回值更改(即使

Rhino Mocks - mocking a method whose return value changes (even when passed the same parameter) with multiple calls(Rhino Mocks - 通过多次调用模拟其返回值更改(即使传递相同的参数)的方法)

本文介绍了Rhino Mocks - 通过多次调用模拟其返回值更改(即使传递相同的参数)的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找如何模拟一个在第二次调用它时返回不同值的方法.例如,像这样:

I'm looking to find out how I can mock a method that returns a different value the second time it is called to the first time. For example, something like this:

public interface IApplicationLifetime
{
    int SecondsSinceStarted {get;}
}

[Test]
public void Expected_mock_behaviour()
{
    IApplicationLifetime mock = MockRepository.GenerateMock<IApplicationLifetime>();

    mock.Expect(m=>m.SecondsSinceStarted).Return(1).Repeat.Once();
    mock.Expect(m=>m.SecondsSinceStarted).Return(2).Repeat.Once();

    Assert.AreEqual(1, mock.SecondsSinceStarted);
    Assert.AreEqual(2, mock.SecondsSinceStarted);
}

有什么可以让这成为可能吗?除了为实现状态机的 getter 实现 sub 之外?

Is there anything that makes this possible? Besides implementing a sub for the getter that implements a state machine?

推荐答案

您可以使用 .WhenCalled 方法截取返回值.请注意,您仍然需要通过 .Return 方法提供一个值,但是如果 ReturnValue 从方法调用中被更改,Rhino 将忽略它:

You can intercept return values with the .WhenCalled method. Note that you still need to provide a value via the .Return method, however Rhino will simply ignore it if ReturnValue is altered from the method invocation:

int invocationsCounter = 1;
const int IgnoredReturnValue = 10;
mock.Expect(m => m.SecondsSinceLifetime)
    .WhenCalled(mi => mi.ReturnValue = invocationsCounter++)
    .Return(IgnoredReturnValue);

Assert.That(mock.SecondsSinceLifetime, Is.EqualTo(1));
Assert.That(mock.SecondsSinceLifetime, Is.EqualTo(2));


再深入研究一下,似乎 .Repeat.Once() 确实 在这种情况下确实有效,并且可以用于实现相同的结果:


Digging around a bit more, it seems that .Repeat.Once() does indeed work in this case and can be used to achieve the same result:

mock.Expect(m => m.SecondsSinceStarted).Return(1).Repeat.Once();
mock.Expect(m => m.SecondsSinceStarted).Return(2).Repeat.Once();
mock.Expect(m => m.SecondsSinceStarted).Return(3).Repeat.Once();

将在连续调用时返回 1、2、3.

Will return 1, 2, 3 on consecutive calls.

这篇关于Rhino Mocks - 通过多次调用模拟其返回值更改(即使传递相同的参数)的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Rhino Mocks - 通过多次调用模拟其返回值更改(即使

基础教程推荐