Home > Blockchain >  Mockito doReturn making list immutable
Mockito doReturn making list immutable

Time:04-14

I'm trying to test a method like this:

public getIndustries(int countryId) {
    var industryList = industryControllerService.getIndustriesByCountryId(countryId);
    ...
    industryList.add(new IndustryCategory(otherIndustry));
}

in my test I have:

List<IndustryCategory> expected = List.of(industryCategory1, industryCategory2);
doReturn(expected).when(industryControllerService).getIndustriesByCountryId(anyInt());
...

But for some reason the industryList is returned by Mockito as an immutable collection, so the add operation throws a UnsupportedOperationException.

How can I change it so that the list is a normal one that can be edited?

CodePudding user response:

List.of returns an immutable list. Try copying it into an ArrayList: expected = new ArrayList<>(List.of(...)).

  • Related