java - 将 List<T> 转换为 Collection<Object[]> 以进行 JUnit 参数化测试

标签 java arrays junit parameterized

我想使用外部数据执行 JUnit 参数化测试。 我有一个对象列表,只需要知道如何将其转换为对象数组的集合。我看到下面的堆栈溢出问题,但我想添加从我的方法读取的文件中的数据。

Parameterized JUnit tests with non-primitive parameters?

工作代码:类似这样:

@RunWith(Parameterized.class)
public class sampletest {

  private BranchMailChildSample branch;

  public sampletest(BranchMailChildSample branch)
  {
    this.branch = branch;
  }

  @Parameters
  public static Collection<Object[]> data()
  {
    String excel = "C:\\Resources\\TestData\\ExcelSheets\\BranchMail\\branchmail_TestData.xlsx";
    ExcelMarshallerTool tool = new ExcelMarshallerTool(excel);
    List<BranchMailChildSample> items = tool.unmarshallExcel(BranchMailChildSample.class);

   //RIGHT HERE I NEED HELP: Convert list to Collection<Object[]>

    //return items as Collection of object arrays 
  }

  @Test
  public void test()
  {
    System.out.println(branch.toString());
  }
}

最佳答案

您不必转换列表。

@RunWith(Parameterized.class)
public class SampleTest {

  @Parameters(name = "{0}")
  public static List<BranchMailChildSample> data() {
    String excel = "C:\\Resources\\TestData\\ExcelSheets\\BranchMail\\branchmail_TestData.xlsx";
    ExcelMarshallerTool tool = new ExcelMarshallerTool(excel);
    return tool.unmarshallExcel(BranchMailChildSample.class);
  }

  @Parameter(0)
  public BranchMailChildSample branch;

  @Test
  public void test() {
    System.out.println(branch.toString());
  }
}

我使用了字段注入(inject),因为它比构造函数注入(inject)需要更少的代码。将名称设置为测试对象会打印更有用的输出。请查看documentation of the Parameterized runner .

如果您不喜欢公共(public)字段,可以使用构造函数注入(inject)。

@RunWith(Parameterized.class)
public class SampleTest {

  @Parameters(name = "{0}")
  public static List<BranchMailChildSample> data() {
    String excel = "C:\\Resources\\TestData\\ExcelSheets\\BranchMail\\branchmail_TestData.xlsx";
    ExcelMarshallerTool tool = new ExcelMarshallerTool(excel);
    return tool.unmarshallExcel(BranchMailChildSample.class);
  }

  private final BranchMailChildSample branch;

  public SampleTest(BranchMailChildSample branch) {
    this.branch = branch;
  }

  @Test
  public void test() {
    System.out.println(branch.toString());
  }
}

关于java - 将 List<T> 转换为 Collection<Object[]> 以进行 JUnit 参数化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29632227/

相关文章:

python - 在 numpy 数组中格式化 float

arrays - PowerShell 中有函数指针或函数数组吗?

java - 内部错误 (javaClasses.cpp :129)

java - 模拟抛出异常的方法

java - 当前不允许连接到相机 "1"

Java json对象替换键名称

java - 如何在方法签名中使用泛型类型?

java - 传递一个类并调用它的方法

c++ - 数组和指针有问题

java - 标记为运行太长的 JUnit 测试失败