Home > Enterprise >  How to unit test a method which calls a void method?
How to unit test a method which calls a void method?

Time:04-07

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 ?

CodePudding user response:

You use the verify method:

verify(myRemovalService).removeData("Test1"));
verify(myRemovalService).removeData("Test2"));

CodePudding user response:

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
  • Related