我有这个接口,在我想模拟的一些函数中返回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行.我发现一些博客说你可以使用lambda(或委托)之类的
Expect.Call(() => mockedInterface.FunctionReturningVoid(param3,param4)); // This doesn't work.
但这对我来说似乎不起作用.拥有Expect.Call可以轻松识别模拟函数,这就是我想要它的原因.我得到的编译错误是:“无法将lambda表达式转换为类型’对象’,因为它不是委托类型”.
那怎么办呢?
解决方法
我更喜欢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();