In my Java service, I use a library to interact with some APIs under the hood andget some response as shown below:
@Service
class CorrectionService {
BookingDetails getData() {
RequestClient <BookingDetails> requestClient = new RequestClient <> (new HttpClientFactory());
ApiResponse <BookingDetails> apiResponse =
requestClient.send(bookingRequest, BookingDetails.class);
return apiResponse.getData();
}
}
RequestClient
is a library util class and I create an object of this class when the method correctionservice.getData()
is called. Note that there are multiple such methods in the CorrectionService
class, each of them creating different types of RequestClient
objects. So, I can't autowire RequestClient
in CorrectionService
.
How can I mock apiResponse
so that it will not actually call requestClient.send()
I tried the below mocking code, but it is still going inside the send()
method of library and calling the actual APIs.
@InjectMocks
CorrectionService correctionService;
@Test
void test(){
RequestClient requestClient = mock(RequestClient.class);
ApiResponse apiResponse = ApiResponse.builder().build();
when(requestClient.send(any(),any(Class.class))).thenReturn(apiResponse);
assertAll(() -> correctionService.getData());
}