'How to unit test a method which calls a void method?
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 ?
Solution 1:[1]
You use the verify method:
verify(myRemovalService).removeData("Test1"));
verify(myRemovalService).removeData("Test2"));
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Johan Nordlinder |
| Solution 2 |
