Pass lambda to parameterized NUnit test

浪子不回头ぞ 提交于 2019-12-03 12:28:05

You can pass exactly that:

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

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("TestCases")]
    public void Test(Func<double, double, double> func)
    {
        Assert.GreaterOrEqual(func(1.0, 1.0), 1.0);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!