Bart van den Burg Bart van den Burg - 3 months ago 62
C# Question

Wrong number of arguments with NUnit TestCaseData

I'm trying to set up some test cases for my test:

public IEnumerable<TestCaseData> size_tests()
{
yield return new TestCaseData(new string[] { "XS", "XL", "M" })
.Returns(new SortedVariantAttributeModel {
Values = new string[] { "XS", "M", "XL" },
PrimaryValue = "XS"
});
}

[Test, TestCaseSource("size_tests")]
public SortedVariantAttributeModel Should_map_SortedVariantAttributes(string[] sizes)
{
// ...
}


When I try to run this test, I get:


Test Failed - Should_map_SortedVariantAttributes("XS","XL","M")

Message: Wrong number of arguments provided


Judging by the error it seems to unwrap the array and try to apply it to the test function, but that results in problems of course. How do I solve this?

Answer

To get this working, you need to wrap the arguments in an array like this, new[] { new string[] { "XS", "XL", "M" } }. This causes NUnit to treat the string array as the first argument to a method instead of a series of string arguments.

I believe that you are using NUnit 2.x because your data source is not static. I simplified your code and tested the workaround in NUnit 2.6.4 and 3.4.1.

public static IEnumerable<TestCaseData> Data()
{
    yield return new TestCaseData(new[] { new string[] { "XS", "XL", "M" } });
    yield return new TestCaseData(new[] { new string[] { "S", "M", "XXL", "L" } });
}

[TestCaseSource(nameof(Data))]
public void TestStringArrayArguments(string[] sizes)
{
    Assert.That(sizes.Length, Is.GreaterThan(1));
}