Is it possible to assign an out
/ref
parameter using Moq (3.0+)?
I've looked at using Callback()
, but Action<>
does not support ref parameters because it's based on generics. I'd also preferably like to put a constraint (It.Is
) on the input of the ref
parameter, though I can do that in the callback.
I know that Rhino Mocks supports this functionality, but the project I'm working on is already using Moq.
EDIT: In Moq 4.10, you can now pass a delegate that has an out or ref parameter directly to the Callback function:
You will have to define a delegate and instantiate it:
For Moq version before 4.10:
Avner Kashtan provides an extension method in his blog which allows setting the out parameter from a callback: Moq, Callbacks and Out parameters: a particularly tricky edge case
The solution is both elegant and hacky. Elegant in that it provides a fluent syntax that feels at-home with other Moq callbacks. And hacky because it relies on calling some internal Moq APIs via reflection.
The extension method provided at the above link didn't compile for me, so I've provided an edited version below. You'll need to create a signature for each number of input parameters you have; I've provided 0 and 1, but extending it further should be simple:
With the above extension method, you can test an interface with out parameters such as:
.. with the following Moq setup:
Edit: To support void-return methods, you simply need to add new overload methods:
This allows testing interfaces such as:
I struggled with many of the suggestions here before I simple created an instance of a new 'Fake' class that implements whatever interface you are trying to Mock out. Then you can simply set the value of the out parameter with the method itself.
For 'out', the following seems to work for me.
I'm guessing that Moq looks at the value of 'expectedValue' when you call Setup and remembers it.
For
ref
, I'm looking for an answer also.I found the following QuickStart guide useful: https://github.com/Moq/moq4/wiki/Quickstart
I struggled with this for an hour this afternoon and could not find an answer anywhere. After playing around on my own with it I was able to come up with a solution which worked for me.
The key here is
mock.SetupAllProperties();
which will stub out all of the properties for you. This may not work in every test case scenario, but if all you care about is getting thereturn value
ofYourMethod
then this will work fine.Seems like it is not possible out of the box. Looks like someone attempted a solution
See this forum post http://code.google.com/p/moq/issues/detail?id=176
this question Verify value of reference parameter with Moq
To return a value along with setting ref parameter, here is a piece of code:
Then declare your own delegate matching the signature of to-be-mocked method and provide your own method implementation.