如何配置 Spring TestRestTemplate
How to configure Spring TestRestTemplate
我有一个 REST (spring-hateoas) 服务器,我想用 JUnit 测试来测试它。因此我使用的是自动注入的 TestRestTemplate
.
但是我现在如何向这个预配置的 TestRestTemplate 添加更多配置?我需要配置rootURI并添加拦截器。
这是我的 JUnit 测试 class:
@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. 但在静态 class 中我无法访问 localServerPort
或 basePath
:
@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 的想法不是吗,这个包装器的整个用例 class?
医生说
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 class 来构建一个配置为我喜欢的 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
}
}
为了配置你的TestRestTemplate,官方documentation建议你使用TestRestTemplate,如下例所示(例如,添加一个Basic Authentication):
public class YourEndpointClassTest {
private static final Logger logger = LoggerFactory.getLogger(YourEndpointClassTest.class);
private static final String BASE_URL = "/your/base/url";
@TestConfiguration
static class TestRestTemplateAuthenticationConfiguration {
@Value("${spring.security.user.name}")
private String userName;
@Value("${spring.security.user.password}")
private String password;
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder().basicAuthentication(userName, password);
}
}
@Autowired
private TestRestTemplate restTemplate;
//here add your tests...
我遇到过一种情况,当时我需要使用 TestRestTemplate
访问我们测试环境中远程服务器上的 REST 端点。因此,测试没有启动 Spring 启动应用程序,而不仅仅是连接到远程端点并从那里使用 REST 服务。测试的配置更简单,执行速度更快,因为它没有构建复杂的 Spring(引导)上下文。这是我的配置的摘录:
@RunWith(SpringRunner.class)
public class RemoteRestTestAbstract {
protected TestRestTemplate restTemplate;
private static RestTemplateBuilder restTemplateBuilder;
@BeforeClass
public static void setUpClass() {
restTemplateBuilder = new RestTemplateBuilder()
.rootUri("http://my-remote-test-server.my-domain.com:8080/");
}
@Before
public void init() {
restTemplate = new TestRestTemplate(restTemplateBuilder);
login();
}
//...
}
我有一个 REST (spring-hateoas) 服务器,我想用 JUnit 测试来测试它。因此我使用的是自动注入的 TestRestTemplate
.
但是我现在如何向这个预配置的 TestRestTemplate 添加更多配置?我需要配置rootURI并添加拦截器。
这是我的 JUnit 测试 class:
@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. 但在静态 class 中我无法访问 localServerPort
或 basePath
:
@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 的想法不是吗,这个包装器的整个用例 class?
医生说
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 class 来构建一个配置为我喜欢的 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
}
}
为了配置你的TestRestTemplate,官方documentation建议你使用TestRestTemplate,如下例所示(例如,添加一个Basic Authentication):
public class YourEndpointClassTest {
private static final Logger logger = LoggerFactory.getLogger(YourEndpointClassTest.class);
private static final String BASE_URL = "/your/base/url";
@TestConfiguration
static class TestRestTemplateAuthenticationConfiguration {
@Value("${spring.security.user.name}")
private String userName;
@Value("${spring.security.user.password}")
private String password;
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder().basicAuthentication(userName, password);
}
}
@Autowired
private TestRestTemplate restTemplate;
//here add your tests...
我遇到过一种情况,当时我需要使用 TestRestTemplate
访问我们测试环境中远程服务器上的 REST 端点。因此,测试没有启动 Spring 启动应用程序,而不仅仅是连接到远程端点并从那里使用 REST 服务。测试的配置更简单,执行速度更快,因为它没有构建复杂的 Spring(引导)上下文。这是我的配置的摘录:
@RunWith(SpringRunner.class)
public class RemoteRestTestAbstract {
protected TestRestTemplate restTemplate;
private static RestTemplateBuilder restTemplateBuilder;
@BeforeClass
public static void setUpClass() {
restTemplateBuilder = new RestTemplateBuilder()
.rootUri("http://my-remote-test-server.my-domain.com:8080/");
}
@Before
public void init() {
restTemplate = new TestRestTemplate(restTemplateBuilder);
login();
}
//...
}