使用 List<string> 类型作为 DataRow 参数

Sha*_*fiz 8 c# parameters attributes unit-testing list

我们如何将 a 传递List<string>DataRow参数[DataTestMethod]

我正在尝试类似的东西:

[DataTestMethod]
[DataRow(new List<string>() {"Iteam1"})]
[TestCategory(TestCategories.UnitTest)]
public void MyTest(IEnumerable<string> myStrings)
{
// ...    
}
Run Code Online (Sandbox Code Playgroud)

我收到编译错误:

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

甚至有可能像这样传递 List 吗?

dee*_*see 21

正如错误消息所述,您不能List在属性中使用s 但可以使用数组。

[DataTestMethod]
[DataRow(new string[] { "Item1" })]
[TestCategory(TestCategories.UnitTest)]
public void MyTest(string[] myStrings)
{
    // ...  
}
Run Code Online (Sandbox Code Playgroud)

要真正使用 aList或任何其他类型,您可以使用DynamicDataAttribute.

[DataTestMethod]
[DynamicData(nameof(GetTestData), DynamicDataSourceType.Method)]
[TestCategory(TestCategories.UnitTest)]
public void MyTest(IEnumerable<string> myStrings)
{
    // ...  
}

public static IEnumerable<object[]> GetTestData()
{
    yield return new object[] { new List<string>() { "Item1" } };
}
Run Code Online (Sandbox Code Playgroud)

提供给 的方法或属性DynamicDataAttribute必须返回IEnumerable对象数组。这些对象数组表示要传递给测试方法的参数。

如果您的列表中始终有固定数量的项目,则可以完全避免使用列表

[DataTestMethod]
[DataRow("Item1", "Item2")]
[TestCategory(TestCategories.UnitTest)]
public void MyTest(string string1, string string2)
{
    // ...  
}
Run Code Online (Sandbox Code Playgroud)


Jes*_*ess 5

我找到了另一种很酷的方法来处理数组!:)

DataRow在MS测试允许你传递params参数。这些将传递到测试方法签名中的数组中。

    [TestMethod]
    [DataRow(true, "")]
    [DataRow(true, "", "")]
    [DataRow(true, "", "", "0")]
    [DataRow(true, "", "", "", "1")]
    [DataRow(true, "", "1", "", "0", "")]
    [DataRow(false, "1")]
    [DataRow(false, "", "1")]
    [DataRow(false, "", "", "1")]
    [DataRow(false, "", "", "1", "1")]
    [DataRow(false, "1", "1", "1", "1")]
    public void IsSparseRow(bool expected, params string[] row)
    {
        // Arrange

        // Act
        var actual = ExcelFileHelpers.IsSparseRow(row);

        // Assert
        Assert.AreEqual(expected, actual);
    }
Run Code Online (Sandbox Code Playgroud)