Search code examples
c#unit-testingmstestdata-driven-testsparameterized-unit-test

How to set 2d array as parameter for unit testing


If expected variable is integer, it simply goes like this

[DataRow(2)]
[TestMethod]
public void TestMethod(int expected)
{
      // some code...
}

But what should one do when there is 2d array int[,] instead of int parameter? When I try to do this

[DataRow(new int[,] { {0, 0}, {0, 0} })]
[TestMethod]
public void TestMethod(int[,] expected)
{
      // some code...
}

error says

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type


Solution

  • You can achieve it by using DynamicData Attribute like below:

    [DataTestMethod]
    [DynamicData(nameof(TestDataMethod), DynamicDataSourceType.Method)]
    public void TestMethod1(int[,] expected)
    {
        // some code...
        var b = expected;
    }
    
    static IEnumerable<object[]> TestDataMethod()
    {
        return new[] { new[] { new int[,] { { 0, 0 }, { 1, 1 } } } };
    }
    

    Output

    enter image description here