我有这个接口,在我想模拟的一些函数中返回void,并想知道这样做的正确方法是什么。截至目前,我有以下内容:
var mocks = new MockRepository();
var mockedInterface = mocks.CreateMock<IMyInterface>();
Expect.Call(mockedInterface.FunctionThatReturn(param1, param2)).Return(Something);
mockedInterface.FunctionReturningVoid(param3, param4);
mocks.ReplayAll();
// Some assert and other stuff
mocks.VerifyAll();
这是正确的做法吗?我觉得它看起来很奇怪,因为你没有以同样的方式处理这两个函数。我想写的是:
var mocks = new MockRepository();
var mockedInterface = mocks.CreateMock<IMyInterface>();
Expect.Call(mockedInterface.FunctionThatReturn(param1, param2)).Return(Something);
Expect.Call(mockedInterface.FunctionReturningVoid(param3, param4)); // This doesn't work.
mocks.ReplayAll();
// Some assert and other stuff
mocks.VerifyAll();
但这不适用于第4行。我发现一些博客说你可以使用lambdas(或委托),如
Expect.Call(() => mockedInterface.FunctionReturningVoid(param3, param4)); // This doesn't work.
但这对我来说似乎没有用。拥有Expect.Call
可以轻松识别模拟函数,这就是我想要它的原因。我得到的编译错误是:“无法将lambda表达式转换为类型'对象',因为它不是委托类型”。
那怎么办?
更新:添加了编译错误信息。
答案 0 :(得分:5)
我更喜欢AAA(编号/动作/断言)语法而不是记录/重放。它更直接,使测试更容易阅读。你想要做的是:
// arrange
var mock = MockRepository.GenerateMock<IMyInterface>
mock.Expect(i => i.FunctionThatReturnSomething(param1, param2)).Return("hello");
mock.Expect(i => i.FunctionThatReturnVoid(param3, param4));
// set up other stuff for your code (like whatever code depends on IMyInterface)
var foo = new Foo(mock);
// act
foo.DoSomething();
// assert
mock.VerifyAll();
答案 1 :(得分:1)
对于void方法,我使用匿名委托:
Expect.Call(delegate { mockedInterface.FunctionReturningVoid(param3, param4); })
BTW:我喜欢Record-Playback语法来重放和验证期望
http://www.ayende.com/Wiki/(S(j2mgwqzgkqghrs55wp2cwi45))/Comparison+of+different+Rhino+Mocks+syntaxes.ashx
答案 2 :(得分:0)
不确定如何在AAA模式中测试void方法,我也无法模拟void。但是,在过去,我使用Record和Playback样式,这应该可行。
示例:
private MockRepository m_mocks = new MockRepository();
private IXGateManager xGateManager = m_mocks.DynamicMock<IXGateManager>();
using (m_mocks.Record())
{
xGateManager.SendXGateMessage(null, null);
LastCall.IgnoreArguments().Repeat.Once();
}
using (m_mocks.Playback())
{
//... execute your test
}