1

I am writing the unit test using moq for a method which has a parameter passed by ref. I need to modify the value of that parameter after the method is called. I am trying using the Callback for Moq setup but it is not updating the value.

myMock = new Mock<IMyObject>();
Foo foo = null;
myMock.Setup(x => x.GetResult(It.IsAny<string>(), ref foo))
          .Returns("SUCCESS")
          .Callback(() => { foo = new Foo ();});

I seen similar question here but they are answered to use callback, but I get the value of foo as null always.

HSharma
  • 385
  • 2
  • 18
  • 2
    Are you ever calling `GetResult`? The call to `Setup` doesn't execute the callback, only actually invoking the method that is being setup (i.e., `GetResult`) will do that. – Patrick Quirk Jan 15 '15 at 15:14
  • Yes I am calling `GetResult` and the still `foo` remains null – HSharma Jan 16 '15 at 04:08
  • This probably not possible. The Callback will not be executed because GetResult with ref parameter 'foo' was not called. You called GetResult, but not with exactly the same instance of ref parameter. Have a look here [link](http://stackoverflow.com/questions/1068095/assigning-out-ref-parameters-in-moq) for some more detals. – Daniel Dušek Jan 16 '15 at 16:56

1 Answers1

0

I was struggling with a similar issue for the past 12 hours and the only way I achieve the results is by manually inheriting and mocking the object.

In your case you can setup a fake object that inherits IMyObject and define it's .GetResult behavior to initialize a new Foo object and then return a "SUCCESS".

You can then use the NUnit api for asserts.

marto
  • 420
  • 1
  • 4
  • 15