繁体   English   中英

Mocking 方法中的依赖项而不是方法本身

[英]Mocking a dependencies in a method instead of the method itself

我开发了一个 class 将我的应用程序与 API 集成在一起。 当我第一次编写测试时,他们实际上正在运行它,但是从长远来看会带来一些复杂性,所以我决定通过 mocking 我的交流来重新编写测试。 这是一种方法的片段,它是测试:

方法确认

public Response confirm(final String key) {
    final Response response;
    try {

        final HttpHeaders httpHeaders = this.initializeHeaders();
        final HttpEntity<String> entity = new HttpEntity<>(httpHeaders);
        final ResponseEntity<String> result = restTemplate.exchange(
                properties.getUri().concat(key),
                HttpMethod.GET,
                entity,
                String.class);

        response = this.handleResultJson(result);

    } catch (Exception e) {
        throw new IntegrationException(e.getMessage());
    }
    return response;
}

及其单元测试

@Test
void ShouldConfirm() {
    final Response response = new Response(
            true,
            UUID.randomUUID().toString(),
            "{\n" +
                    "    \"key\": \"dd227b53-550b-44a1-bb61-01016c3821ff\",\n" +
                    "    \"lastUpdated\": " + LocalDateTime.now() + ",\n" +
                    "}"
    );
    when(service.confirm(KEY)).thenReturn(response);
    assertEquals(service.confirm(KEY), response);
}

即使在我写它的时候,我也觉得它很奇怪。 我似乎根本不会从原始方法中调用任何代码。 但是由于我是 mockito 的新手,所以我继续前进。 在我运行声纳之后,毫不奇怪,我发现我的覆盖率下降了很多。 我在同一件事上发现了这个问题,而 Jon Skeet 的回答一直都是正确的。 我的问题是:在我的情况下,我如何仅模拟 API 的实际响应?

阅读链接中的问题,我意识到我真正需要嘲笑的是以下内容:

final ResponseEntity<String> result = restTemplate.exchange(
                properties.getUri().concat(key),
                HttpMethod.GET,
                entity,
                String.class);

因为我不想实际调用端点,所以只测试整个方法。 我该如何做到这一点? 似乎很困难,因为result是我要测试的方法中的一个变量。

你需要模拟如下的resttemplate

@Mock
private RestTemplate restTemplate ;

restTemplate.exchange()

ResponseEntity<String> responseEntity = new ResponseEntity<String>("sampleBodyString",HttpStatus.OK);

when(restTemplate.exchange(
                           Matchers.anyString(), 
                           Matchers.any(HttpMethod.class),
                           Matchers.<HttpEntity<?>> any(), 
                           Matchers.<Class<String>> any()
                          )
                         ).thenReturn(responseEntity);

暂无
暂无

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

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