How to test a method parameter type jagged array with XUnit

1000 Views Asked by At

How can I test a method that takes a parameter of type string[][] ? I tried using InlineData attribute but it only works with string[]

[InlineData(new string[]{ "one", "two", "three"})]

but not with

[InlineData(new string[][] { new string[]{"one"}, new string[] {"two" } })]

What is the correct way to do it ?

1

There are 1 best solutions below

1
On

Jagged Array as Argument only works by using the 'params' keyword. The jagged array must be the last argument of the test method. See my example:

[Theory]
[InlineData(2, 3,
    new[] { "val1", "val2", "val3" },
    new[] { "val4", "val5", "val6" }
)]
[InlineData(3, 2,
    new[] { "val1", "val2" },
    new[] { "val3", "val4" },
    new[] { "val4", "val5" }
)]
public void MyTestMethod(int exptectedOuterCount, int expectedInnerCount, params string[][] myArray)
{
    Assert.Equal(exptectedOuterCount, myArray.Length);

    foreach (var innerArray in myArray)
    {
        Assert.Equal(expectedInnerCount, innerArray.Length);
    }
}

Without the params-keyword the compiler do not accept the jagged array.