简体   繁体   中英

Using mockito when thenReturn with a new object

I've got the following line of code in my implementation:

myService.getTypes(new TypeRequest(myList.stream().map(Object::toString)
                        .collect(Collectors.toList())))

and I tried to mock the above in my test class as follows:

when(myService.getTypes(new TypeRequest(Lists.newArrayList("15", "16"))))
                .thenReturn(Lists.newArrayList(type1, type2));
when(myService.getTypes(new TypeRequest(Lists.newArrayList("25", "26"))))
                .thenReturn(Lists.newArrayList(type3, type4));

But when I debug the test code, I can see that myService.getTypes is returning an empty list. What could be the problem?

Also, is there a way to use args to simplify the above mocking? All I found was using args passed into the method, not the args of args passed into the method.

Found the solution:

when(myService.getTypes(any(TypeRequest.class)))
    .thenAnswer(invocationOnMock -> {
        TypeRequest r = invocationOnMock.getArgument(0);
        //if r contains "15"
            return Lists.newArrayList(type1, type2);
        } else {
            return Lists.newArrayList(type3, type2);
        }
});

By default, it uses equals() of the input argument to check if it is matched with any stubbed parameters. Most probably you do not implement TypeRequest 's equals() , so no stubbed parameters are matched and hence it returns the default result for the unstubbed invocation which is an empty list.

If you do not want to implement equals() for TypeRequest , the correct way is to use argThat() to define a ArgumentMatcher for the input argument :

@Test
public void someTest(){
    
    when(myService.getTypes(argThat(requestListContainAll(Lists.newArrayList("15", "16")))))
                  .thenReturn(Lists.newArrayList(type1, type2));
    myService.getTypes(Lists.newArrayList("15", "16"))); //it should return the above stubbed value
}


private ArgumentMatcher<TypeRequest> requestListContainAll(List<String> list){
    return arg-> arg.getList().containsAll(list);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM