I am trying to validate a scheduled task in a spring-boot application. A static method is called in the flow. Using mockedStatic works as expected when the service class is tested standalone, but not when the service is called as part of the scheduled task. When testing the scheduler, the static method is making the real method call.
Thanks in advance for any assistance.
@RequiredArgsConstructor
@Component
public class ConnectionHandler
private final ConnectionService connectionService;
private final RequestMapper requestMapper;
@Scheduled(cron="${scheduler.cronTime}")
public void processService() {
...
List<String> idList = getIdList();
idList.forEach(id ->{
var cronRequest = createRequest(id)
sendRequest(cronRequest);
});
}
void sendRequest(CronRequest cronRequest) {
Mono.just(cronRequest)
.doOnNext(request -> log.debug("start request for {}", request.id))
.flatMap(request -> requestMapper.mapRequest(id))
.flatMap(hostRequest -> connectionService->sendRequest(hostRequest))
.onErrorResume(RequestException.class, ex -> log.error("Service error {}-{}", ex.getHttpStatus(), ex.getResponse()))
response -> requestMapper.mapResponse(response))
.contextWrite(RequestUtils.getContext(id))
.block();
}
@ExtendWith(OutputCaptureExtension.class)
@SpringBootTest
@TestPropertySource(locations = "/application-test.properties")
class ConnectionHandlerTest {
@Test
void testScheduledService(CapturedOutput capturedOutput) {
try{MockedStatic<RequestFactory> ignored = mockStatic(RequestFactory.class)) {
RequestConfig requestConfig = new RequestConfig();
requestConfig.setHostIp("10.10.10.10");
requestConfig.setPort(443)
when(RequestFactory.getRequestConfig("ID1")).thenReturn(requestConfig);
await().atMost(2, TimeUnit.MINUTES).untilAsserted(() -> {
assertEquals(1, capturedOutput.getAll().lines.collect(Collectors.toList()).stream.filter(entry -> entry.contains("request completed")).count());
});
}
assertFalse(capturedOutput.getAll().lines.collect(Collectors.toList()).stream.anyMatch(entry -> entry.contains("Service error")));
}
}
I tried the MockedStatic within the await also. Using spring-boot version 2.7.10 mockito-inline v5.1.1