I got a problem might not be possible to resolve but I still want to see if anyone has any suggestion.
Please see the MyService and MyServiceTest Java classes below.
I tried to make the restTemplate mock persist as there is a line of code in my actual method (demo using the callExternalService()). Meaning, when I run the test, I want to have the restTemplate.exchange to always return the responseEntityTest dummy values.
Is it possible? right now, there always a null pointer exception since the “this restTemplate = null” will erase the mock.
Thank you!
*/imports....*
@Service
public class MyService {
private RestTemplate restTemplate;
@Autowired
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String callExternalService() {
String url = "https://api.example.com/resource";
this.restTemplate = null; //just for demo the problem
HttpEntity<String> requestEntity = new HttpEntity<>(null);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
return response.getBody();
}
}
*/some imports*
public class MyServiceTest {
@Mock
private RestTemplate restTemplateMock;
@InjectMocks
private MyService myService;
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testCallExternalService() {
// Mocking the RestTemplate's behavior
ResponseEntity<String> responseEntityTest = new ResponseEntity<>("Mocked Response", HttpStatus.OK);
when(restTemplateMock.exchange(
anyString(),
any(HttpMethod.class),
any(HttpEntity.class),
any(Class.class)
)).thenReturn(responseEntityTest);
// Calling the method under test
String response = myService.callExternalService();
// Verifying the response
assertEquals("Mocked Response", response);
}
}
I tried to make the restTemplate mock persist as there is a line of code in my actual method (demo using the callExternalService()). Meaning, when I run the test, I want to have the restTemplate.exchange to always return the responseEntityTest dummy values.
Is it possible? right now, there always a null pointer exception since the “this restTemplate = null” will erase the mock.