There appears to be inadequate documentation on setting up expectations in NMock for methods that accept arguments by reference using “out” and “ref” keywords. Here is a quick note to give an example demonstrating how it can be done.
Consider the following interface:
public interface IFoo
{
void Bar(out int a, ref int b);
}
“Bar” method takes one “out” parameter and another “ref” parameter.
To start mocking “IFoo” you would obviously first create a new mock object implementing interface “IFoo”.
IFoo aFoo = mocks.NewMock< IFoo >();
We store it in a variable named “aFoo”.
Here’s how you would set up an expectation to ask NMock to expect a call to method “Bar” on “aFoo” object with an “out” parameter and a “ref” parameter with 2 as its value.
Expect.Once.On(aFoo)
.Method(“Bar”).With(Is.Out, 2)
.Will(new SetNamedParameterAction(“a”, 10),
new SetNamedParameterAction(“b”, 20));
The actions specified in the “Will” part cause the “out” and “ref” parameters to be set to values 10 and 20 respectively after “Bar” is called on “aFoo”.
int a, b = 2;
aFoo.Bar(out a, ref b);
// At this point “a” will be set to 10 and “b” will be set to 20 because
// of the expectation specified above.
Hope this helps.
Sandeep
May 21, 2010
hi. thanks
Ajit
August 20, 2010
thanks, it helped, i was stuck right there.
Ajit
Robert
May 23, 2011
Thanks, Siddharth. We were stuck on this, too. We switched from NUnit.Mock to NMock2 just for this feature.
Nik
March 26, 2013
NMock3:
int i=1;
var handler = m_mockFactory.CreateMock();
handler.Expects.One.Method(m => m.GetQueryResult(new Query(), 1, 10, out i))
.With(Is.Match(q => q.GetQuery() == “”), 1, 10, Is.Out);