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.
Mocking this using Moq is pretty straightforward: _mockSub = "subword"; _testOrthoepedia = new Mock<IOrthoepedia>(MockBehavior. Strict); _testOrthoepedia .
The Moq framework is an open source unit testing framework that works very well with .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With