Rhino Mocks - mocking a method whose return value changes (even when passed the same parameter) with multiple calls(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 - 通过多次调用模拟其返回值更改(即使传递相同的参数)的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Rhino Mocks - 通过多次调用模拟其返回值更改(即使
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01