NMock expectations for functions accepting “ref” and “out” arguments

Posted on November 17, 2008


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.

.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.

About these ads
Posted in: General