Post

Mocking functions taking variable number of args using C# params keyword

In .NET on December 16, 2008 by Sid Tagged:

Consider the following interface that takes a variable number of arguments in its Add method.

public interface IAdder
{
string Add(params string[] items);
}

And consider that we have to test the following function which invokes Add with two arguments.

public string AddStrings(string one, string two, IAdder adder)
{
return adder.Add(one, two);
}

The expectation created below is incorrect:

string[] args = new string[] { “FOO”, “BAR” };
IAdder adder = mocks.NewMock();
string expected = “FOOBAR”;

Expect.Once.On(adder).Method(“Add”).With(args).Will(Return.Value(expected));

string actual;
actual = target.AddStrings(args[0], args[1], adder);
Assert.AreEqual(expected, actual);

It will cause NMock to generate the following exception because NMock is expecting two distinct arguments to Add with values “FOO” and “BAR” instead of an array of strings containing “FOO” and “BAR”.

NMock2.Internal.ExpectationException occurred
Message=”unexpected invocation of adder.Add()\r\nExpected:\r\n 1 time: adder.Add(equal to \”FOO\”, equal to \”BAR\”), will return \”FOOBAR\” [called 0 times]\r\n”

You need to change the expectation so that NMock compares the string-array.

Expect.Once.On(adder).Method(“Add”).With(Is.EqualTo(args)).Will(Return.Value(expected));

That’ll do the trick.


One Response to “Mocking functions taking variable number of args using C# params keyword”

  1. As you explain, you have to paa an array of elements for a params argument. That’s because from the methods view it’s an array and not several different arguments.

    But,I’m currently playing around with the internals of NMock2 (http://sourceforge.net/projects/nmock2) to extend the matching of method arguments in a way that it will be possible to use

    .With(“FOO”, “BAR”)

    If I get it right (it’s a bit tricky :-O) then it will be in the next version of NMock2.

    Happy mocking
    Urs

Leave a Reply