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

Posted on December 16, 2008

1


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.

About these ads
Tagged:
Posted in: .NET