gpt4 book ai didi

java - 如何配置Spring TestRestTemplate

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

我有一个 REST (spring-hateoas) 服务器,我想用 JUnit 测试来测试它。因此,我正在使用自动注入(inject)的 TestRestTemplate

但是我现在如何向这个预配置的 TestRestTemplate 添加更多配置?我需要配置 rootURI 并添加拦截器。

这是我的 JUnit 测试类:

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

public class RestEndpointTests {
private Logger log = LoggerFactory.getLogger(this.getClass());

@LocalServerPort
int localServerPort;

@Value(value = "${spring.data.rest.base-path}") // nice trick to get basePath from application.properties
String basePath;

@Autowired
TestRestTemplate client; // how to configure client?

[... here are my @Test methods that use client ...]
}

The documentation sais that a static @TestConfiguration class can be used.但是在该静态类中我无法访问 localServerPortbasePath:

  @TestConfiguration
static class Config {

@Bean
public RestTemplateBuilder restTemplateBuilder() {
String rootUri = "http://localhost:"+localServerPort+basePath; // <=== DOES NOT WORK
log.trace("Creating and configuring RestTemplate for "+rootUri);
return new RestTemplateBuilder()
.basicAuthorization(TestFixtures.USER1_EMAIL, TestFixtures.USER1_PWD)
.errorHandler(new LiquidoTestErrorHandler())
.requestFactory(new HttpComponentsClientHttpRequestFactory())
.additionalInterceptors(new LogRequestInterceptor())
.rootUri(rootUri);
}

}

我最重要的问题:为什么 TestRestTemplate 不考虑 application.properties 中的 spring.data.rest.base-path首先? beeing complete preconfigured 的想法不是这个包装类的整个用例吗?

医生说

If you are using the @SpringBootTest annotation, a TestRestTemplate is automatically available and can be @Autowired into you test. If you need customizations (for example to adding additional message converters) use a RestTemplateBuilder @Bean.

完整的 Java 代码示例看起来如何?

最佳答案

我知道这是一个老问题,您现在可能已经找到了另一个解决方案。但无论如何,我正在为其他像我一样绊倒的人回答。我有一个类似的问题,并最终在我的测试类中使用 @PostConstruct 来构建一个配置为我喜欢的 TestRestTemplate,而不是使用 @TestConfiguration。

    @RunWith(SpringJUnit4ClassRunner.class)
@EnableAutoConfiguration
@SpringBootTest(classes = {BackendApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyCookieClientTest {
@LocalServerPort
int localPort;

@Autowired
RestTemplateBuilder restTemplateBuilder;

private TestRestTemplate template;

@PostConstruct
public void initialize() {
RestTemplate customTemplate = restTemplateBuilder
.rootUri("http://localhost:"+localPort)
....
.build();
this.template = new TestRestTemplate(customTemplate,
null, null, //I don't use basic auth, if you do you can set user, pass here
HttpClientOption.ENABLE_COOKIES); // I needed cookie support in this particular test, you may not have this need
}
}

关于java - 如何配置Spring TestRestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42272521/

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