我在阅读 Roy Osherove 的同时开始尝试 Rhino-Mocks (3.6)单元测试的艺术。他有一个示例,演示了可以编写模拟方法的脚本,以便在使用相同参数调用两次时返回不同的结果:
[Test]
public void ReturnResultsFromMock()
{
MockRepository repository = new MockRepository();
IGetRestuls resultGetter = repository.DynamicMock<IGetRestuls>();
using(repository.Record())
{
resultGetter.GetSomeNumber("a");
LastCall.Return(1);
resultGetter.GetSomeNumber("a");
LastCall.Return(2);
resultGetter.GetSomeNumber("b");
LastCall.Return(3);
}
int result = resultGetter.GetSomeNumber("b");
Assert.AreEqual(3, result);
int result2 = resultGetter.GetSomeNumber("a");
Assert.AreEqual(1, result2);
int result3 = resultGetter.GetSomeNumber("a");
Assert.AreEqual(2, result3);
}
这很好用。但是,当我使用存根和接受并返回字符串的方法尝试相同的操作时,我无法生成第二个返回值:
[Test]
public void StubMethodWithStringParameter_ScriptTwoResponses_SameResponseReceived()
{
MockRepository mocks = new MockRepository();
IMessageProvider stub = mocks.Stub<IMessageProvider>();
using (mocks.Record())
{
stub.GetMessageForValue("a");
LastCall.Return("First call");
stub.GetMessageForValue("a");
LastCall.Return("Second call");
}
Assert.AreEqual("First call", stub.GetMessageForValue("a"));
Assert.AreEqual("Second call", stub.GetMessageForValue("a"));
}
}
public interface IMessageProvider
{
string GetMessage();
string GetMessageForValue(string value);
}
此测试失败,因为两个呼叫都收到“First Call”。我已经尝试了几种语法(使用mocks.Ordered()、SetResult、Expect 等),但仍然无法显示第二个结果。
我做错了什么,还是这是 Rhino-Mocks 的限制?我已经检查过这个博客文章,但建议的语法没有解决我的问题。
您缺少的部分是告诉存根第一个值只应返回一次:
...
using (mocks.Record())
{
stub.GetMessageForValue("a");
LastCall.Return("First call").Repeat.Once();
stub.GetMessageForValue("a");
LastCall.Return("Second call");
}
当然,除非您对 Repeat 施加其他限制,否则您的“第二次调用”实际上意味着“第二次或后续调用”。
您还可以考虑使用较新的 Arrange、Act、Assert (AAA) 语法 RhinoMocks 现在提供:
[Test]
public void StubMethodWithStringParameter_ScriptTwoResponses_SameResponseReceived()
{
IMessageProvider stub = MockRepository.GenerateStub<IMessageProvider>();
stub.Expect(mp => mp.GetMessageForValue("a"))
.Return("First call")
.Repeat.Once();
stub.Expect(mp => mp.GetMessageForValue("a"))
.Return("Second call");
Assert.AreEqual("First call", stub.GetMessageForValue("a"));
Assert.AreEqual("Second call", stub.GetMessageForValue("a"));
}
它更加简洁,通常可以让您不必担心存根的记录播放断言状态。德里克·贝利写了一篇关于使用重复的文章在洛斯泰奇斯。它也恰好使用了 AAA 语法)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)