通过lambda来参数NUnit测试(Pass lambda to parameterized NU

2019-07-29 15:37发布

我有一帮运算符重载的类:

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

对于所有的人我想测试操作数为空。 我有一个NUnit测试为:

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));
}

如何传递的λ为每个操作员等(l,r) => l + r

Answer 1:

您可以通过正是:

MatrixOperatorOperandIsNullThrows((l,r) => l + r);


Answer 2:

你不能立即应用的TestCase属性包含lambda表达式,即下面的测试将是无效的:

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

你能做什么,但是,是使用TestCaseSource有一个IEnumerable您的lambda表达式的属性一起,就像这样:

[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("TestCases")]
    public void Test(Func<double, double, double> func)
    {
        Assert.GreaterOrEqual(func(1.0, 1.0), 1.0);
    }
}


文章来源: Pass lambda to parameterized NUnit test