0

I am trying to use Moq to mock a method with two OUT parameters. This should work according to the Moq samples here: https://code.google.com/p/moq/wiki/QuickStart

var moqDB = new Mock<IMyDB>();

int Value1 = 500000;
decimal Value2 = 0.2M;

moqDB.Setup(db => db.DoSomething(out Value1, out Value2)).Returns(true);

But it does not set the values within the method I'm testing:

public virtual void TestMethod(IMyDB db)
{
    int Value1 = 0;
    decimal Value2 = 0.0M;

    db.DoSomething(out Value1, out Value2);

    // Check Values
}

What am I doing wrong?

Ryan Gates
  • 4,501
  • 6
  • 50
  • 90
Joe Davis
  • 233
  • 3
  • 11
  • I don't know this is the problem but in the example the out variables are declared as `var`'s rather than their types. I'd try give that a try. Also, just gonna point out; I can't find anything about how `out` params work and in the example they set the out param to the value it 'returns' - is it actually doing anything at all? – evanmcdonnal Mar 15 '13 at 19:05
  • Good thought. Tried it and it didn't make any difference. – Joe Davis Mar 15 '13 at 19:08
  • What are you trying to verify? Technically, the two out fields don't need to be initialized before passing them to `DoSomething`. Are you just trying to make sure `DoSomething` is called? Or that the out arguments hold the expected values? – Travis Parks Mar 15 '13 at 19:08
  • Within the method logic it performs work with the out values. So in order for the remainder of the code to be tested, that method needs to return values that with drive the code path. – Joe Davis Mar 15 '13 at 19:10
  • related: http://stackoverflow.com/questions/1068095/assigning-out-ref-parameters-in-moq – Ben Voigt Mar 15 '13 at 19:10
  • One option (probably not the answer your looking for) is to _not use out parameters_. Return an custom type instead. – jrummell Mar 15 '13 at 19:13
  • Typically arguments values are only used to match calls. If you say you expect `foo("abc")`, you won't match `foo("def")`. This has weird implications when working with `out` parameters where you expect the opposite behavior. – Travis Parks Mar 15 '13 at 19:18
  • I'd recommend looking at [NSubstitute](http://nsubstitute.github.com/help/setting-out-and-ref-arguments/). I prefer the library and it has this functionality built-in. – Travis Parks Mar 15 '13 at 19:20

1 Answers1

1

moq doesn't actually change the out values. In the example you posted they initialize the out value to the value they want (var outString = "ack";). In your code you start them at 0 and expect the function to return the proper values.

I don't see any documents that indicate you can moq out values. Instead your code should just be;

public virtual void TestMethod(IMyDB db)
{
    int Value1 = 500000;
    decimal Value2 = 0.2M;

    db.DoSomething(out Value1, out Value2);

    // look the out values are 500000 and .2M, OMG!!!
 }

kind of lame...

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115