RhinoMocks的 - 嘲讽多次调用的返回值改变(即使通过相同的参数)的方法 [英] RhinoMocks - mocking a method whose return value changes (even when passed the same parameter) with multiple calls
问题描述
我期待找出我怎么能嘲笑返回不同的值它被称为第一次,第二次的方法。例如,这样的事情:
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);
}
这有什么,使这个可能吗?除了实施实现了一个状态机的吸气剂子?
Is there anything that makes this possible? Besides implementing a sub for the getter that implements a state machine?
干杯家伙,
亚历
推荐答案
您可以拦截返回值与 .WhenCalled
方法。请注意,您仍然需要通过 .Return
方法来提供价值,但是犀牛将简单地忽略它,如果返回值
从改变方法调用:
You can intercept return values with .WhenCalled
method. Note that you still need to provide value via .Return
method, however Rhino will simply ignore it if ReturnValue
is altered from 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 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.
这篇关于RhinoMocks的 - 嘲讽多次调用的返回值改变(即使通过相同的参数)的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!