Java 模拟方法中的依赖项而不是方法本身
我开发了一个类,将我的应用程序与API集成在一起。当我第一次编写测试时,他们实际上是在运行它,但从长远来看,这带来了一些复杂性,所以我决定通过模仿我的交流来重构测试。以下是一种方法的截图及其测试: 方法确认:Java 模拟方法中的依赖项而不是方法本身,java,spring,mockito,junit5,Java,Spring,Mockito,Junit5,我开发了一个类,将我的应用程序与API集成在一起。当我第一次编写测试时,他们实际上是在运行它,但从长远来看,这带来了一些复杂性,所以我决定通过模仿我的交流来重构测试。以下是一种方法的截图及其测试: 方法确认: public Response confirm(final String key) { final Response response; try { final HttpHeaders httpHeaders = this.initializeHeader
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);
}
即使在我写的时候,我也觉得很奇怪。我觉得mock根本不会调用原始方法中的任何代码。但因为我对莫基托不熟悉,所以我一直坚持。在我运行声纳后,我发现,毫不奇怪,我的覆盖率下降了。我在同一件事上发现了,Jon Skeet的答案一直都是正确的。我的问题是:在我的例子中,我如何只模拟依赖性,来自API的atual响应?
阅读链接中的问题,我意识到我真正需要嘲笑的只有以下几点:
final ResponseEntity<String> result = restTemplate.exchange(
properties.getUri().concat(key),
HttpMethod.GET,
entity,
String.class);
final ResponseEntity result=restemplate.exchange(
properties.getUri().concat(键),
HttpMethod.GET,
实体,
字符串(类);
因为我不想实际调用端点,所以只需测试整个方法。我如何做到这一点?似乎很难,因为
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);
@Mock
私有RestTemplate RestTemplate;
restemplate.exchange()
ResponseEntity ResponseEntity=新的ResponseEntity(“sampleBodyString”,HttpStatus.OK);
何时(restemplate.exchange)(
Matchers.anyString(),
Matchers.any(HttpMethod.class),
Matchers.Get Acquired with dependency injection pattern:这正是我所需要的。我如何使确认方法仅在从单元测试运行时获得模拟响应?您所说的“仅在从单元测试用例运行时”是什么意思?作为替代方法,您可以使用