Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass lambda to parameterized NUnit test

I have a class with a bunch of overloaded operators:

public static double[,] operator +(Matrix matrix, double[,] array)
public static double[,] operator -(Matrix matrix, double[,] array)
public static double[,] operator *(Matrix matrix, double[,] array)

For all of them I'd like to test operands for null. I have an NUnit test for that:

public void MatrixOperatorOperandIsNullThrows(Func<Matrix, double[,], double[,]> op)
{
    Matrix m = null;
    var right = new double[,] {{1, 1}, {1, 1}};
    Assert.Throws<ArgumentException>(() => op(m, right));
}

How can I pass a lambda for each operator like (l,r) => l + r ?

like image 860
Andrey Ermakov Avatar asked May 30 '12 19:05

Andrey Ermakov


2 Answers

You cannot immediately apply the TestCase attribute containing a lambda expression, i.e. the following test would be invalid:

[TestCase((a, b) => a + b)]
public void WillNotCompileTest(Func<double, double, double> func)
{
    Assert.GreaterOrEqual(func(1.0, 1.0), 1.0);
}

What you can do, however, is to use the TestCaseSource attribute together with an IEnumerable of your lambda expressions, like this:

[TestFixture]
public class TestClass
{
    private IEnumerable<Func<double, double, double>> testCases
    {
        get
        {
            yield return (a, b) => a + b;
            yield return (a, b) => a * b;
            yield return (a, b) => a / b;
        }
    }

    [TestCaseSource(nameof(testCases))]
    public void Test(Func<double, double, double> func)
    {
        Assert.GreaterOrEqual(func(1.0, 1.0), 1.0);
    }
}
like image 181
Anders Gustafsson Avatar answered Oct 16 '22 10:10

Anders Gustafsson


You can pass exactly that:

MatrixOperatorOperandIsNullThrows((l,r) => l + r);
like image 21
SLaks Avatar answered Oct 16 '22 11:10

SLaks