【发布时间】:2019-10-28 19:52:33
【问题描述】:
我正在尝试为进行 http 调用的 rest 模板编写单元测试。我已经使用其余模板生成器创建了其余模板,如下所示。其余模板设置为配置读取和连接超时。我还有一个重试模板,用于在应用程序超时时执行重试。我已经指定了 http 方法:postForEntity、exchange 和 getForEntity,它们需要在重试模板中重试,并且需要帮助编写单元测试。我从 getForEntity 方法开始,但收到的输出与预期不同。对此的任何帮助都会有所帮助。
休息模板
@Bean
public RestTemplate restTemplate() {
return new RestTemplateBuilder()
.setConnectTimeout(Duration.ofSeconds(10))
.setReadTimeout(Duration.ofSeconds(10))
.build();
}
正在重试 getForEntity
public ResponseEntity getForEntity(URI uri, Class c) {
return retryTemplate.execute(retryContext -> {
return restTemplate.getForEntity(uri, c);
});
}
单元测试
public class RetryRestTemplateTest {
@Mock
private RestTemplate restTemplate;
@Mock
private RetryTemplate retryTemplate;
private RetryRestTemplate retryRestTemplate;
String testUrl = "http://localhost:8080";
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
retryRestTemplate = new RetryRestTemplate(
restTemplate,
retryTemplate
);
}
@Test
public void getForEntity() throws URISyntaxException{
URI testUri= new URI(testUrl);
ArgumentCaptor<URI> argument = ArgumentCaptor.forClass(URI.class);
doReturn(new ResponseEntity<>("ResponseString", HttpStatus.OK))
.when(restTemplate).getForEntity(any(URI.class), eq(String.class));
assertThat(restTemplate.getForEntity(testUri, String.class), is(HttpStatus.OK));
verify(restTemplate).getForEntity(argument.capture(), eq(String.class));
assertThat(argument.getValue().toString(), is(testUri));
}}
我的预期应该是 而我的实际应该是 >
这方面的任何帮助都会有所帮助,因为我对 Mockito 和 Junit 没有那么丰富的经验。
【问题讨论】:
-
您要验证/测试什么?
-
我正在尝试测试 getForEntity 方法
标签: java unit-testing mockito resttemplate