[英]Rhino Mocks - mocking a method whose return value changes (even when passed the same parameter) with multiple calls
我正在尋找如何模擬一個在第二次被調用到第一次時返回不同值的方法。 例如,這樣的事情:
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 之外?
您可以使用.WhenCalled
方法攔截返回值。 請注意,您仍然需要通過.Return
方法提供一個值,但是如果從方法調用中更改了ReturnValue
,Rhino 將簡單地忽略它:
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()
確實不工作在這種情況下,可以用來實現相同的結果:
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。
只需使用
mock.Expect(m=>m.SecondsSinceStarted).Return(1).Repeat.Once();
mock.Expect(m=>m.SecondsSinceStarted).Return(2).Repeat.Once();
這將在第一次調用期間返回1
,在第二次調用期間返回2
。 至少在 Rhino Mocks 3.6.0.0 中。
如果時間是該方法返回的決定因素,我會嘗試抽象出時間流逝,以便您可以在測試中直接控制它。
類似於名為 ITimeProvider 的接口和名為 GetElapsedTime() 的成員,然后創建一個默認實現以在整個應用程序中使用。
然后,當您進行測試時,傳入一個模擬的 ITimeProvider,以便您控制應用程序所感知的時間傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.