gpt4 book ai didi

java - 在 Spring 集成测试中模拟 RestTemplateBuilder 和 RestTemplate

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:19:26 25 4
gpt4 key购买 nike

我有一个 REST 资源,它获取一个 RestTemplateBuilder 注入(inject)来构建一个 RestTemplate:

public MyClass(final RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}

我想测试那个类。我需要模拟 RestTemplate 对另一个服务的调用:

request = restTemplate.getForEntity(uri, String.class);

我在我的 IT 中试过这个:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyIT {

@Autowired
private TestRestTemplate testRestTemplate;
@MockBean
private RestTemplateBuilder restTemplateBuilder;
@Mock
private RestTemplate restTemplate;

@Test
public void shouldntFail() throws IOException {

ResponseEntity<String> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
when(restTemplateBuilder.build()).thenReturn(restTemplate);
when(restTemplate.getForEntity(any(URI.class), any(Class.class))).thenReturn(responseEntity);
...
ResponseEntity<String> response = testRestTemplate.postForEntity("/endpoint", request, String.class);
...
}
}

当我运行测试时,出现以下异常:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.test.web.client.TestRestTemplate': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: RestTemplate must not be null

如何正确执行此操作?

最佳答案

您的问题是执行顺序。在您有机会在您的 @Test 中设置它之前,会创建包含您的 MockBean 的上下文。解决方案是提供一个 RestTemplateBuilder,它在插入上下文时已经完全设置好。你可以这样做。

将以下内容添加到您的 @SpringBootTest 注释中。其中 TestApplication 是您的 Spring Boot 应用程序类。

classes = {TestApplication.class, MyIT.ContextConfiguration.class},

因此修改您的类成员,删除您的 restTemplate 和 restTemplateBuilder。

@Autowired
private TestRestTemplate testRestTemplate;

将静态内部类添加到您的 MyIT 类:

@Configuration
static class ContextConfiguration {
@Bean
public RestTemplateBuilder restTemplateBuilder() {

RestTemplateBuilder rtb = mock(RestTemplateBuilder.class);
RestTemplate restTemplate = mock(RestTemplate.class);

when(rtb.build()).thenReturn(restTemplate);
return rtb;
}
}

在你的测试中,修改 RestTemplate mock 来做任何你想做的事:

@Test
public void someTest() {

when(testRestTemplate.getRestTemplate().getForEntity(...
}

关于java - 在 Spring 集成测试中模拟 RestTemplateBuilder 和 RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49128616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com