10

我正在使用 NUnit 并尝试为以下方法实现测试:它应该接受两个整数并返回二维数组。因此,我的测试标题如下所示:

[TestCase(5, 1, new int[,]{{1}, {2}, {3}, {4}, {5}})]
public void MyTestMethod(int a, int b, int[][] r)

在编译期间,我遇到以下错误:

错误 CS0182:属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式 (CS0182)


我知道可以使用TestCaseSource引用对象数组来完成,例如以下问题的答案:

给出如下代码:

private object[][] combination_tests =  new [] {
    new object[] {5, 1, new [,]{{1}, {2}, {3}, {4}, {5}}},
};

[Test]
[TestCaseSource("combination_tests")]
public void MyTestMethod(int a, int b, int[,] r)

但我仍然有一个问题:是否可以只使用TestCase属性来做到这一点?

4

2 回答 2

5

您是否绝对有必要为您的方法使用相同的签名,即

public void MyTestMethod(int a, int b, int[][] r)
{
    // elided
}

根据您的情况,您有两个可用选项,这两个选项都使用[TestCase]您在问题中所说的属性:

是否可以仅使用TestCase属性来做到这一点?

我更喜欢第一个选项,因为它感觉更简洁,但两者都会满足您的需求。


选项 1:如果不需要保持相同的签名

您可以稍微修改签名,而不是数组(不是编译时常量),而是传入一个字符串(这是编译时常量),该字符串可用于获取数组,例如

private static int[][] getArrayForMyTestMethod(string key)
{
    // logic to get from key to int[][]
}

[TestCase(5, 1, "dataset1")]
public void MyTestMethod(int a, int b, string rKey)
{
    int[][] r = getArrayForMyTestMethod(rKey);
    // elided
}

选项 2:如果需要保持相同的签名

如果需要为方法保留相同的签名,您可以使用与选项 1 相同的包装方法,即

private static int[][] getArrayForMyTestMethod(string key)
{
    // logic to get from key to int[][]
}

[TestCase(5, 1, "dataset1")]
public void MyTestMethodWrapper(int a, int b, string rKey)
{
    int[][] r = getArrayForMyTestMethod(rKey);
    MyTestMethod(a, b, r);
}

public void MyTestMethod(int a, int b, int[][] r)
{
    // elided
}

显然,您可以使用任何可以是编译时常量的类型,而不是 astring取决于测试用例的构造方式,但我建议使用 a string,因为您可以通过这种方式在 NUnit 运行器中为您的测试用例命名.


否则,您的替代方法是使用[TestCaseSource]您在问题中提到的方法。

于 2015-04-21T06:38:08.607 回答
4

您可以使用 testcasedata 对象将结果传递给

    public IEnumerable<TestCaseData> combination_tests()
        {
          yield return new TestCaseData(5,1,new int[,] {{1}, {2}, {3}, {4}, {5}});
        }

    [Test]
    [TestCaseSource("combination_tests")]
    public void test(int a, int b, int[,] r)
        {

            Console.WriteLine(r[0,0] & r[1,0]);

        }

您还可以使用 .SetName("xxx") 或 .SetCategory("xxx") 为每个 testCaseData 项目设置测试类别和测试名称,这对于组织测试非常有用。

于 2015-04-20T16:29:26.197 回答