And*_*kov 9 c# nunit parameterized
我有一个带有一堆重载运算符的类:
public static double[,] operator +(Matrix matrix, double[,] array)
public static double[,] operator -(Matrix matrix, double[,] array)
public static double[,] operator *(Matrix matrix, double[,] array)
Run Code Online (Sandbox Code Playgroud)
对于所有这些我想测试操作数为null.我有一个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));
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能为每个运营商传递一个lambda (l,r) => l + r?
And*_*son 23
您不能立即应用包含lambda表达式的TestCase属性,即以下测试将无效:
[TestCase((a, b) => a + b)]
public void WillNotCompileTest(Func<double, double, double> func)
{
Assert.GreaterOrEqual(func(1.0, 1.0), 1.0);
}
Run Code Online (Sandbox Code Playgroud)
但是,你可以做的是将TestCaseSource属性与lambda表达式的IEnumerable一起使用,如下所示:
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
你完全可以通过:
MatrixOperatorOperandIsNullThrows((l,r) => l + r);
Run Code Online (Sandbox Code Playgroud)