How to make Moq ignore arguments that are ref or out

c#, moq

Solution

As you already figured out the problem is with your `ref` argument.

Moq currently only support exact matching for `ref` arguments, which means the call only matches if you pass the same instance what you've used in the `Setup`. So there is no general matching so `It.IsAny()` won't work.

See Moq quickstart

// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);

And Moq discussion group:

Ref matching means that the setup is matched only if the method is called with that same instance. It.IsAny returns null, so probably not what you're looking for.

Use the same instance in the setup as the one in the actual call, and the setup will match.

Problem

In RhinoMocks, you can just tell your mocks to IgnoreArguments as a blanket statement. In Moq, it seems, you have to specify It.IsAny() for each argument. However, this doesn't work for ref and out arguments. How can I test the following method where I need to Moq the internal service call to return a specific result: ``` public void MyMethod() { // DoStuff IList<SomeObject> errors = new List<SomeObject>(); var result = _service.DoSomething(ref errors, ref param1, param2); // Do more stuff } ``` Test method: ``` public void TestOfMyMethod() { // Setup var moqService = new Mock<IMyService>(); IList<String> errors; var model = new MyModel(); // This returns null, presumably becuase "errors" // here does not refer to the same object as "errors" in MyMethod moqService.Setup(t => t.DoSomething(ref errors, ref model, It.IsAny<SomeType>()). Returns(new OtherType())); } ``` UPDATE: So, changing errors from "ref" to "out" works. So it seems like the real issue is having a ref parameter that you can't inject.

Original source