Rhino Mocks-模拟一个方法,该方法的多次调用会改变返回值(即使传递了相同的参数) [英] Rhino Mocks - mocking a method whose return value changes (even when passed the same parameter) with multiple calls

查看:66
本文介绍了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-模拟一个方法,该方法的多次调用会改变返回值(即使传递了相同的参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆