Using Rhino Mocks to mock an out parameter, which is created within the method I am testing

ctrlplusb picture ctrlplusb · Jul 29, 2010 · Viewed 13k times · Source

Trying to mock the following method:

bool IsLoginValid(LoginViewModel viewModel, out User user);

Tried this initially:

dependency<ILoginService>()
.Stub(serv =>
        serv.IsLoginValid(
            Arg<LoginViewModel>.Is.Equal(a_login_viewmodel),
            out Arg<User>.Is.Anything)
.Return(false);

But, that fails, as it is an out parameter. Did a bit of searching around and altered my code like such:

dependency<ILoginService>()
.Stub(serv => 
        serv.IsLoginValid(
            Arg<LoginViewModel>.Is.Equal(a_login_viewmodel), 
            out Arg<User>.Out(new User()).Dummy))
.Return(false);

That also fails. I need 'new User()' to be sort of an 'Anything' argument. As I think that is expecting a specific instance.

Any idea how to get around this? Thanks guys.

Answer

PatrickSteele picture PatrickSteele · Jul 29, 2010

Try the "OutRef" option. It accepts a params object[] that defines the result for each out parameter. Since you've only got one, you only need one result. Here's a quick mock-up of what I tried that should work in your situation:

var foo = MockRepository.GenerateStub<IFoo>();
var viewModel = new LoginViewModel();
User temp;
foo.Stub(f => f.IsLoginValid(viewModel, out temp)).OutRef(new User()).Return(false);

User outparam;
Assert.IsFalse(foo.IsLoginValid(viewModel, out outparam));