两个字符串数组的单元测试
Unit test for two string arrays
我的单元测试中的以下数据行会在两个字符串数组依次出现时抛出一条错误消息,但在我将另一种数据类型置于其间时则不会。
[TestClass]
public class UnitTest
{
[TestMethod]
// invalid
[DataRow(new string[] { }, new string[] { })]
// valid
[DataRow(new string[] { }, 8, new string[] { })]
public void TestMethod(string[] input, string[] output)
{
var solution = new Program();
CollectionAssert.AreEqual(output, solution.Method(input));
}
}
并且我得到以下错误(第 6 行),属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式。我在构造函数中定义了数组,那么它怎么不是常量呢?提前谢谢你。
DataRow
属性中的第二个参数是 params object[] moreData
。
您传递的 new string[] { }
与 object[]
不同,这就是您收到错误的原因。
试试这个:
[DataRow(new string[] { }, new object[] { new string[] { } })]
public void TestMethod(string[] input, string[] output) {}
它将对象数组正确映射到字符串。
但您可能会考虑使用 DynamicData
属性来传递复杂值。
我的单元测试中的以下数据行会在两个字符串数组依次出现时抛出一条错误消息,但在我将另一种数据类型置于其间时则不会。
[TestClass]
public class UnitTest
{
[TestMethod]
// invalid
[DataRow(new string[] { }, new string[] { })]
// valid
[DataRow(new string[] { }, 8, new string[] { })]
public void TestMethod(string[] input, string[] output)
{
var solution = new Program();
CollectionAssert.AreEqual(output, solution.Method(input));
}
}
并且我得到以下错误(第 6 行),属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式。我在构造函数中定义了数组,那么它怎么不是常量呢?提前谢谢你。
DataRow
属性中的第二个参数是 params object[] moreData
。
您传递的 new string[] { }
与 object[]
不同,这就是您收到错误的原因。
试试这个:
[DataRow(new string[] { }, new object[] { new string[] { } })]
public void TestMethod(string[] input, string[] output) {}
它将对象数组正确映射到字符串。
但您可能会考虑使用 DynamicData
属性来传递复杂值。