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 - 通过多次调用模拟其返回值更改(即使


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04