【问题标题】:Pass an array as attribute-value将数组作为属性值传递
【发布时间】:2016-11-13 06:06:19
【问题描述】:

我有一个测试方法如下:

[TestCase(new string[] { "1", "2", "5" }, Result = true)]
bool AllocateIDsTest1(IEnumerable<string> expected)
{
    var target = ...
    var actual = target.AllocateIDs(expected);

    return actual.SequenceEqual(expected);
}

但是我得到一个编译器错误:

属性参数必须是属性参数类型的常量表达式、typeof表达式或数组创建表达式。

可能编译器无法区分以下构造函数:

TestCase(params object[] args, Named Parameters);

TestCase(object ob1, Named Paramaters);

因为new string[] { "1", "2", "5" } 可以同时解析为params object[]object

来自this post 我知道字符串数组应该可以作为编译常量传递。

如何向TestCase 提供字符串数组?

【问题讨论】:

    标签: c# attributes nunit


    【解决方案1】:

    我找到了使用 params-approach 的解决方案:

    [TestCase("1", "2", "5", Result = true)]
    public bool AllocateIDsTest1(params string[] expected)
    {
        var target = ...
        var actual = target.AllocateIDs(expected);
    
        return actual.SequenceEqual(expected);
    }
    

    【讨论】:

    • 出色的解决方法。另一种选择是使用 TestCaseSource,请参阅文档。
    • 甚至没有解决方法。 :-) 这就是应该使用 TestCase 的方式。编译器错误不是因为您传入了一个数组 - 这在属性上是明确允许的。这是因为您要求属性构造函数使用 new 动态创建数组。 C# 不允许这样做。
    • @Charlie 那么,当您说“属性明确允许”时,究竟应该如何将数组分配给属性?通过static 字段?
    猜你喜欢
    • 2022-11-11
    • 1970-01-01
    • 2018-05-13
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多