0

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"));
    }
dariosicily
  • 4,239
  • 2
  • 11
  • 17
John Seen
  • 701
  • 4
  • 15
  • 31
  • does this answer your question : https://stackoverflow.com/questions/25564533/how-to-mock-remote-rest-api-in-unit-test-with-spring – dassum May 16 '21 at 04:50

1 Answers1

0

If you want to mock an external api. You have to mock it using some simulator for HTTP apis. I have been using wiremock for such cases, it's quite easy to use. You can find plenty of tutorial about the same. You can check this out.

Anil Bhaskar
  • 3,718
  • 4
  • 33
  • 51