繁体   English   中英

如何(单元)测试方法向 MS Teams 频道发送 http 请求?

[英]How to (unit) test method sending http request to MS Teams channel?

我编写了一个监控服务 class 执行数据库检查某个(被认为是错误的)state 的条目。 根据数据库查询的结果,该服务将使用其连接器/Webhook 功能向 Microsoft Teams 频道发送通知。 到目前为止一切正常,但我不知道如何正确测试各自的方法。 这主要是向我正在努力解决的团队发送通知的方法:

public HttpStatus sendNotificationToTeams(MsTeamsCard card) throws JsonProcessingException {
        HttpHeaders headers = new HttpHeaders();
        ObjectWriter writer = new ObjectMapper().writer();
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(WebConfig.PROXY_HOST, WebConfig.PROXY_PORT));
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

        // Setup RestTemplate. Proxy is required, otherwise request returns HTTP 500 with misleading error message (array index out of bounds)
        requestFactory.setProxy(proxy);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        // HTTP request incl. setup
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity<>(writer.writeValueAsString(card), headers);
        ResponseEntity<String> response = restTemplate.exchange(this.webhookUrl, HttpMethod.POST, request, String.class);
        return response.getStatusCode();
    }

我认为我绝对应该测试这种方法,因为它根本不是微不足道的。 但是,我认为在这种方法内部并没有太多可能会失败的原因,这与其特定的代码安排有关——当然可能存在问题,但是网络问题之类的事情不在此方法的(单元)测试的 scope。 那么我将如何可靠地测试这种方法呢? 我从一般测试的角度(这是我真正缺乏知识的地方)要求更多,而不是请求测试框架或其他东西的具体帮助(顺便说一句,使用 JUnit 4)。 例如,有一点是,即使我模拟它,我也无法检查 HTTP 调用的结果,因为它需要 Teams 的特定回答:请求可能成功,但 Teams 可能有问题,我可以t真的嘲笑那个。 但也许我在这里想得太复杂了。

如果您正在寻找对您的 http 连接器进行单元测试,您可以使用 Wiremock 来完成。 看看这个教程

例如

@Test
public void shouldSendNotification() {
  String path = "/endpoint";
  wiremock.stubFor(get(urlEqualTo(path))
          .willReturn(aResponse()
                  .withStatus(200))
  );
  HttpStatus status = sendNotificationToTeams(...);
  assertThat(status).isEqualTo(200);
}

暂无
暂无

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

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