0

I'm trying to write a reusable method for unit tests to be able to mock the behaviour for a certain class which returns a List<String>, so that I can call this mockInstansiate method to set up the mock. How do I pass in multiple lists for the thenReturn() method? I know I could do .thenReturn().thenReturn().thenReturn etc, but I was hoping to be able to make this dynamic as I won't know how many lists I will have.

The error I am getting is:

Cannot create a generic array of ArrayList<String>

Code:

private void mockInstansiate (List<String> wheels) {
    Machine machine = mock(Machine.class);
    List<List<String>> results = new ArrayList<List<String>>();

    for(String wheel : wheels) {
        List<String> result = new ArrayList<String>();
        result.add(wheel);

        results.add(result);
    }

    List<String> wheel1 = results.remove(0);

    /* Issue here, I'm trying to create an array of List<String> to pass
     * into the second part of thenReturn() */
    List<String>[] otherLists = new ArrayList<String>[9];
    when(machine.getLists()).thenReturn(wheel1, results.toArray(otherLists));
}

class Machine {
    public List<String> getLists() {
        // Doesn't matter what's here, it's being mocked out
    }
}
Fodder
  • 564
  • 1
  • 10
  • 23
  • Regarding the duplicate, I was able to solve your problem using the second solution (e.g. `List[] otherLists = new List[9];`). You'll need to suppress a unchecked warning. Do also read the comments in detail in the duplicate as they provide warnings you should heed. – Duncan Jones Oct 09 '14 at 13:06
  • @Duncan, when I try the second solution, passing that into `toArray()` results in an `ArrayStoreException`. I'm guessing that means that it can't copy the objects over as the types don't match. The linked solution works though. Thanks. – Fodder Oct 09 '14 at 21:39

0 Answers0