Search code examples
javaarraysjunitparameterized

Convert List<T> to Collection<Object[]> for JUnit Parametrized Test


I would like to perform a JUnit Parametrized test with data being external. I have a list of objects and just need to know how I can convert that to a collection of object arrays. I see the below stack overflow question, but I want to add data from a file which is read from my method.

Parameterized JUnit tests with non-primitive parameters?

Working code: something like this:

@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());
  }
}

Solution

  • You don't have to convert the list.

    @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());
      }
    }
    

    I used field injection, because it needs less code than constructor injection. Setting the name to the object under test prints more helpful output. Please have a look at the documentation of the Parameterized runner.

    You can use constructor injection if you don't like the public field.

    @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());
      }
    }