Search code examples
powermockexpectations

How to expect a new arraylist object in powermock?


I have a code which has below two new List objects of different type:

List<TypeOne> typeOneList =  new ArrayList<TypeOne>();
List<TypeTwo> typeTwoList =  new ArrayList<TypeTwo>();

How can I use PowerMock.expectNew() to return two different ArrayList objects? Like..

PowerMock.expectNew(ArrayList.class).andReturn(typeOneList);
PowerMock.expectNew(ArrayList.class).andReturn(typeTwoList);

How we can differentiate in the above statement as for which statement the objects corresponds to?

thanks!


Solution

  • Well. You have to define in the below way in the order you want..

    PowerMock.expectNew(ArrayList.class).andReturn(typeOneList); //first expect list object of TypeOne
    PowerMock.expectNew(ArrayList.class).andReturn(typeTwoList); //then expect list object of TypeTwo
    

    and powermock will return the objects in the order of expectations when the below code executes:

    List<TypeOne> typeOneList =  new ArrayList<TypeOne>();
    List<TypeTwo> typeTwoList =  new ArrayList<TypeTwo>();