Home > Net >  Mockito mock method input value passed as reference with given output value
Mockito mock method input value passed as reference with given output value

Time:09-20

Given the following method:

public void method(Long a, Long b, Set<Long> out) {
    out.add(42L);
}

I would like to mock the out parameter that is modified upon running:

Set<Long> x = new HashSet<>();
x.add(1L);

Mockito.doNothing().when(service).method(anyLong(), anyLong(), any());
// How to mock the last parameter with x?

Question:

How can achieve that upon serivce run, the Set<Long> out parameter is mocked with a predefined value?

CodePudding user response:

I think an Answer is what you need:

Mockito.doAnswer(i -> {
    Set<Long> out = i.getArgument(2);
    out.add(42L);
    return out;
}).when(service)).method(anyLong(), anyLong(), any());

CodePudding user response:

Has the Set<Long> out attribute a getter? If that's the case, you can do something like:

when(service.getOut()).thenReturn(42L);
  • Related