2

I am stuck with a basic issue for unit testing a scenario and will appreciate help.

I have a class MyService which calls MyRemovalService to set a flag to true in the DB.


@Slf4j
@Service
@RequiredArgsConstructor
public class MyService {

    private final MyRemovalService myRemovalService;
    private final MyRepository myRepository;

    public void setFlag() {
        final List<String> records = myRepository.getData(ENUM_1, ENUM_2, ENUM_3);
        records.forEach(MyRemovalService::removeData);
    }

}


MyTest:

@ExtendWith(MockitoExtension.class)
class MyServiceTest {

    @Mock
    private MyRemovalService myRemovalService;

    @Mock
    private MyRepository myRepository;

    @InjectMocks
    private MyService myService;

    @Test
    void testMyUseCase() {
        when(myRepository.getData(any(), any(), any())).thenReturn(List.of("Test1", "Test2"));
        myService.setFlag();
    }

}

I have been asked to test and check if (MyRemovalService::removeData) is being called with relevant data.

How can I test this since the return type is void ?

newLearner
  • 637
  • 1
  • 12
  • 20
  • Have a look at Mockito's `ArgumentCaptor`, you can capture the params sent to the method. And assert that they are correct afterwards – Bentaye Apr 06 '22 at 13:58
  • Does this answer your question? [Java verify void method calls n times with Mockito](https://stackoverflow.com/questions/27787487/java-verify-void-method-calls-n-times-with-mockito) – HariHaravelan Apr 06 '22 at 14:04

2 Answers2

3

You use the verify method:

verify(myRemovalService).removeData("Test1"));
verify(myRemovalService).removeData("Test2"));
Johan Nordlinder
  • 1,672
  • 1
  • 13
  • 17
1

Mockito allows to define ArgumentCaptors that allows you to capture the arguments methods of mocked objects were called with:

var objectRequestedForRemovalCapture = ArgumentCaptor.forClass(String.class);
verify(myRemovalService).removeData(objectRequestedForRemovalCapture.capture());
var results = objectRequestedForRemovalCapture.getAllValues();

//and do the verification on your list of objects
void
  • 144
  • 8