c# - 如何在 Xunit 中测试使用 List<List<T> 作为输入参数的方法

标签 c# .net tdd xunit xunit.net

我想用 List<List<string>> 测试一个方法作为参数。我使用 xunit 作为测试框架。

这是我尝试过的。

public static IEnumerable<IEnumerable<string>> CombinationData
{
    get
    {
        return new List<List<string>>
        {
            new List<string>{ "a", "b", "c" }, 
            new List<string>{ "x", "y", "z" }
        };
    }
}

[Theory]
[MemberData(nameof(CombinationData))]
public void CombinationDataTest(List<List<string>> dataStrings)
{
     ...
}

运行测试时出现以下异常。

System.ArgumentException :
Property CombinationData on CodeUnitTests.MainCodeTests yielded an item that is not an object[]
Stack Trace: at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()

我该如何让它发挥作用?这是正确的方法吗?

最佳答案

错误信息非常清楚。提供的功能为MemberData应该返回IEnumerable<object[]> ,其中

  • IEnumerable的每一项是一个测试用例的参数集合
  • 每个 objectobject[]是测试方法期望的参数

您的测试方法期望 List<List<string>>作为参数,因此您应该返回 List<List<string>> 的实例作为 object[] 的第一项

private static IEnumerable<object[]> CombinationData()
{
    var testcase = new List<List<string>>
    {
        new List<string>{ "a", "b", "c" }, 
        new List<string>{ "x", "y", "z" }
    };  
    yield return new object[] { testcase };
}

关于c# - 如何在 Xunit 中测试使用 List<List<T> 作为输入参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45947690/

相关文章:

unit-testing - 协调单元测试与 OOD

ruby - 我如何测试(TDD)单例类?

c# - 反射、属性和属性选择

c# - 必须使用 OUTPUT INTO 声明标量变量 '@ID'

c# - Console.WriteLine() 的高内存使用率

c# - 垃圾回收如何处理对象引用?

c# - 在不同的通用 List<T> 中搜索常见项目,我怎样才能做得更好?

php - MySqlConnection 打开失败,即使模拟也拒绝访问

c# - 在 C#.net 后面的代码中发送短信的换行符

testing - 使用 TypeORM 和 Nestjs 进行测试的过程,以及使用 mocks 开玩笑的过程?