【问题标题】:Using the 'TestCase' attribute with a two-dimensional array将“TestCase”属性与二维数组一起使用
【发布时间】:2015-04-18 18:51:36
【问题描述】:

我正在使用 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 属性来做到这一点?

【问题讨论】:

  • (现有答案的总结)这是 .NET 属性系统的限制,因此它不是 NUnit 缺陷。因此,要解决此限制,必须 (1) 将数据重新格式化为 .NET 属性系统允许的数据类型,或 (2) 存储在类字段、属性或可以创建和返回NUnit 加载单元测试项目时的数据。其他 .NET 单元测试框架也会有同样的问题。

标签: c# arrays nunit testcaseattribute


【解决方案1】:

您的方法是否绝对需要具有相同的签名,即

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
}

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


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

【讨论】:

    【解决方案2】:

    可以使用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-03-24
      • 2012-02-21
      • 1970-01-01
      • 2023-03-30
      • 2015-07-30
      • 2020-10-24
      • 2010-11-17
      • 2011-05-06
      • 2016-04-11
      相关资源
      最近更新 更多