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 - 通过多次调用模拟其返回值更改(即使传递相同的参数)的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)