简体   繁体   English

JUnit 测试 Mocking 测试用例 Springboot App

[英]JUnit test Mocking test case for Springboot App

Working on a Springboot app, which has a method to make a call to external rest API and get some response.使用 Springboot 应用程序,该应用程序具有调用外部 rest API 并获得一些响应的方法。 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.这个响应是一个介于 1 和 100 之间的数字。我正在使用一个简单的 if else 循环来检查数字是小于还是大于 50。

This works fine.这工作正常。 But as I am new to Springboot, I am not able to write a Junit test case for this.但由于我是 Springboot 新手,我无法为此编写 Junit 测试用例。 I am not sure how to Mock this.我不知道如何模拟这个。

Controller 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.在看到一些示例后,我添加了一些 Junit 测试用例,但它不起作用。 How do I mock the external rest API.如何模拟外部 rest API。 For now lets assume the external API is not reachable for Junit cases.现在让我们假设外部 API 对于 Junit 案例是不可访问的。

   @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"));
    }

If you want to mock an external api.如果要模拟外部 api。 You have to mock it using some simulator for HTTP apis.您必须使用 HTTP apis 的一些模拟器来模拟它。 I have been using wiremock for such cases, it's quite easy to use.在这种情况下,我一直在使用wiremock ,它很容易使用。 You can find plenty of tutorial about the same.你可以找到很多相同的教程。 You can check this out .你可以看看这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM