問(wèn)題描述
我正在尋找如何模擬一個(gè)在第二次調(diào)用它時(shí)返回不同值的方法.例如,像這樣:
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);
}
有什么可以讓這成為可能嗎?除了為實(shí)現(xiàn)狀態(tài)機(jī)的 getter 實(shí)現(xiàn) sub 之外?
Is there anything that makes this possible? Besides implementing a sub for the getter that implements a state machine?
推薦答案
您可以使用 .WhenCalled
方法截取返回值.請(qǐng)注意,您仍然需要通過(guò) .Return
方法提供一個(gè)值,但是如果 ReturnValue
從方法調(diào)用中被更改,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()
確實(shí) 在這種情況下確實(shí)有效,并且可以用于實(shí)現(xiàn)相同的結(jié)果:
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();
將在連續(xù)調(diào)用時(shí)返回 1、2、3.
Will return 1, 2, 3 on consecutive calls.
這篇關(guān)于Rhino Mocks - 通過(guò)多次調(diào)用模擬其返回值更改(即使傳遞相同的參數(shù))的方法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!