I have a SpringBoot Service class. I am writing Junit for one of the method which internally calls multiple method of the same class. Internal method also calls another method. I tried using when-thenReturn, but isn'tworking for me. Please give me some leads as I am very much new to Mockito and Junit. I am getting error while making resttemplate call hence I mocked that. Also my testcase for only thirdMethod(-) is working as expected. Also, I am only mocking expected response from public method not private.
@Service
public class MyService{
public void flow(RequestObject request){
//request processsing
firstMethod(firstRequestObj);
//some logic
secondMethod(secondRequestObj);
//some logic
}
private FirstResponse firstMethod(FirstRequestObj firstRequestObj){
//some logic
thirdMethod(thirdRequestObj);
//some logic
return firstResponse;
}
private SecondResponse secondMethod(SecondRequestObj secondRequestObj){
//some logic
thirdMethod(thirdRequestObj);
//some logic
return secondResponse;
}
public ResponseEntity<ThirdResponse> thirdMethod(ThirdRequestObj thirdRequestObj){
//some logic
try {
ResponseEntity<ThirdResponse> response = restTemplate.exchange(
url, HttpMethod.POST, entity, ThirdResponse.class);
return response ;
} catch (Exception e) {
//exception handled
}
}
}
@InjectMock @Spy
Myservice myService;
@ParameterizedTest
@DisplayName("Should check the flow")
@MethodSource("com.web.test.utilities.TestUtils#getRequest")
public void flowTest(Request request){
when(restTemplate.exchange(ArgumentMatchers.<String>any(), eq(HttpMethod.POST),
ArgumentMatchers.<HttpEntity>any(),
eq(String.class))).thenReturn(any(ResponseEntity.class));
when(myService.thirdMethod(any())).thenReturn(any());
myService.flow(someRequest);
//myService.flow(any());
}