我有一个包含一堆重载运算符的类:
public static double[,] operator +(Matrix matrix, double[,] array)
public static double[,] operator -(Matrix matrix, double[,] array)
public static double[,] operator *(Matrix matrix, double[,] array)
对于所有这些我想测试操作数为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));
}
如何为每个运算符传递lambda,例如(l,r) => l + r
?
答案 0 :(得分: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);
}
然而,你可以做的是将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);
}
}
答案 1 :(得分:1)
你可以完全通过:
MatrixOperatorOperandIsNullThrows((l,r) => l + r);