【问题标题】:JUnit test Mocking test case for Springboot AppSpringboot App的JUnit测试Mocking测试用例
【发布时间】:2021-08-04 14:00:20
【问题描述】:

在 Springboot 应用程序上工作,该应用程序具有调用外部 rest API 并获得一些响应的方法。这个响应是一个介于 1 和 100 之间的数字。我正在使用一个简单的 if else 循环来检查数字是小于还是大于 50。

这很好用。但是由于我是 Springboot 的新手,所以我无法为此编写 Junit 测试用例。我不知道如何模拟这个。

控制器

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;
}

我在看到一些示例后添加了一些 Junit 测试用例,但它不起作用。如何模拟外部休息 API。现在让我们假设 Junit 案例无法访问外部 API。

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

【问题讨论】:

标签: java spring-boot junit mockito resttemplate


【解决方案1】:

如果你想模拟一个外部 api。您必须使用一些 HTTP api 模拟器来模拟它。对于这种情况,我一直在使用wiremock,它很容易使用。你可以找到很多相同的教程。 You can check this out.

【讨论】:

    猜你喜欢
    • 2018-07-06
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2019-11-27
    相关资源
    最近更新 更多