Working on a Springboot app, which has a method to make a call to external rest API and get some response. This response is a number between 1 and 100. I am using a simple if else loop to check if number is less than or greater than 50.
This works fine. But as I am new to Springboot, I am not able to write a Junit test case for this. I am not sure how to Mock this.
Controller
private final Logger logger = LoggerFactory.getLogger(getClass());
private static RestTemplate restTemplate1 = new RestTemplate();
private static final String baseURL = "url/path";
@GetMapping("/compare")
public String compareToFifty() {
ResponseEntity<String> responseEntity = restTemplate1.getForEntity(baseURL, String.class);
String response1 = responseEntity.getBody();
String message = "Could not determine comparison";
if (Integer.parseInt(response1) > 50) {
message = "Greater than 50";
logger.info(message);
} else {
message = "Smaller than or equal to 50";
logger.info(message);
}
return message;
}
I add some Junit test case after seeing some examples but it doesn't work. How do I mock the external rest API. For now lets assume the external API is not reachable for Junit cases.
@Test
public void smallerThanOrEqualToFiftyMessage() throws Exception {
this.mockMvc.perform(get("/compare")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string("Smaller than or equal to 50"));
}