Search code examples
c#.netunit-testingmstest

How to provide int[,] and int values to test method, C#


I need this method for unit testing. There is matrix and method that calculate matrix trace which is integer. So i need to provide simple matrix (int[,]) and expected trace:

[DynamicData(nameof(TestDataMethod), DynamicDataSourceType.Method)]
public void TestReturnTrace(int[,] simpleMatrix, int expected)
{
    var mock = new Mock<IMatrixGenerator>();

    mock.Setup(a => a.GenerateRandomMatrix()).Returns(simpleMatrix);

    MatrixBase matrix = new MatrixBase(mock.Object);

    int actual = matrix.ReturnTrace();

    Assert.AreEqual(expected, actual);
}

How can i create simple 2D array and integer value and return it?

My best attempt is:

    static IEnumerable<object[], int> TestDataMethod()
    {
        int[,] array2d = new int[,] { { 1, 0 }, { 0, 1 } };
        int myInteger = 2;

        return (new[] { 
            new[] { array2d }, 
            myInteger )
        };
    }

but the error is "No best type found for implicitly-typed array", like if I try to create array, but I just pair two values in parentheses. Where am I wrong?


Solution

  • Your return type doesn't match the method data, you can use tuple (int[,], int) as generic type parameter for IEnumerable<T> and yield return to return a single item.

    static IEnumerable<(int[,], int)> TestDataMethod()
    {
        int[,] array2d = { { 1, 0 }, { 0, 1 } };
        int myInteger = 2;
    
        yield return (array2d, myInteger);
    }
    

    Update: just looked at some articles regarding MSTest and DynamicData attribute, like this. The correct approach seems to be using an IEnumerable<object[]>, where every item in object array represents a single argument in test method

    static IEnumerable<object[]> TestDataMethod()
    {
        int[,] array2d = { { 1, 0 }, { 0, 1 } };
        int myInteger = 2;
    
        yield return new object[] { array2d, myInteger };
    }