在RhinoMocks中模拟void函数的正确方法是什么?

Tom*_*son 7 .net c# rhino-mocks mocking

我有这个接口,在我想模拟的一些函数中返回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();
Run Code Online (Sandbox Code Playgroud)

这是正确的做法吗?我觉得它看起来很奇怪,因为你没有以同样的方式处理这两个函数.我想写的是:

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();
Run Code Online (Sandbox Code Playgroud)

但这不适用于第4行.我发现一些博客说你可以使用lambda(或委托)之类的

Expect.Call(() => mockedInterface.FunctionReturningVoid(param3, param4)); // This doesn't work.
Run Code Online (Sandbox Code Playgroud)

但这对我来说似乎不起作用.拥有Expect.Call它可以轻松识别模拟功能,这就是我想要的原因.我得到的编译错误是:"无法将lambda表达式转换为类型'对象',因为它不是委托类型".

那怎么办呢?

更新:添加了编译错误信息.

Pat*_*ele 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();
Run Code Online (Sandbox Code Playgroud)


Ser*_*kiy 1

对于 void 方法,我使用匿名委托:

Expect.Call(delegate { mockedInterface.FunctionReturningVoid(param3, param4); })
Run Code Online (Sandbox Code Playgroud)

顺便说一句:我喜欢用于重放和验证期望的记录播放语法 http://www.ayende.com/Wiki/(S(j2mgwqzgkqghrs55wp2cwi45))/Comparison+of+ different+Rhino+Mocks+syntaxes.ashx