35

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.

ctrlplusb
  • 12,847
  • 6
  • 55
  • 57

2 Answers2

49

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));
PatrickSteele
  • 14,489
  • 2
  • 51
  • 54
16

Changing the accepted answer (by @Patrick Steele) to match the variable names and whitespace in the question:

.Stub(serv => serv.IsLoginValid(
            a_login_viewmodel, 
            out temp)).OutRef(new User())
.Return(false);

...then changing the syntax (but not the semantics) to the fluent Args syntax:

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

...then we end up with exact same syntax as the OP's second attempt, which apparently "fails". Personally, I prefer the fluent 'Args' style, even though it is slightly more verbose.

TL;DR the OP's second attempt is semantically equivalent to the accepted answer, merely uses a different syntax.

onedaywhen
  • 55,269
  • 12
  • 100
  • 138
  • I don't get it, the fluent Args syntax example in your answer is the same as @ctrlplusb second approach. He complains that this is not running either. Am I missing something? – Anton Kalcik Mar 31 '16 at 15:01
  • @AntonKalcik: what *_I_* don't get is why the OP says "That worked perfectly" and accepts it as The One True Answer when it is semantically equivalent to something he originally said "fails". My answer essentially says, don't abandon a superior syntax just because you unwittingly corrected a bug when you rewrote the thing." – onedaywhen Apr 01 '16 at 08:33
  • You are right, want just ask, because I was confused. I tried it and your syntax mimic exactly Patrick Steel's code. – Anton Kalcik Apr 01 '16 at 13:15