RhinoMocks - 存根返回参数的方法

Mar*_*tin 36 unit-testing rhino-mocks mocking stubbing

我正在使用RhinoMocks,我需要存根一个方法,并且总是让它返回第三个参数,无论传入什么:

_service.Stub(x => x.Method(parm1, parm2, parm3)).Return(parm3);
Run Code Online (Sandbox Code Playgroud)

显然,这并不容易.我并不总是知道parms会是什么,但我知道我总是希望返回第3个.

Wim*_*nen 66

您可以使用Do()处理程序为方法提供实现:

Func<TypeX,TypeY,TypeZ,TypeZ> returnThird = (x,y,z) => z;
mock.Expect(x => x.Method(null, null, null)).IgnoreArguments().Do(returnThird);
Run Code Online (Sandbox Code Playgroud)

请注意,它TypeZ出现两次,因为它既是输入参数类型又是返回类型.


Jon*_*Rea 6

这对我有用:

        _service
            .Stub(x => x.Method(Arg<string>.Is.Anything, ... ))
            .Return(null) // ... or default(T): will be ignored but RhinoMock requires it
            .WhenCalled(x =>
            {
                // This will be used as the return value
                x.ReturnValue = (string) x.Arguments[0];
            });
Run Code Online (Sandbox Code Playgroud)