测试工具
一些在测试应用程序时通常非常有用的测试工具类已打包为 spring-boot
的一部分。
ConfigDataApplicationContextInitializer
ConfigDataApplicationContextInitializer 是一个 ApplicationContextInitializer,你可以将其应用于测试中以加载 Spring Boot 的 application.properties
文件。当你不需要 @SpringBootTest 提供的完整功能集时,可以使用它,如下例所示:
- Java
- Kotlin
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(classes = Config.class, initializers = ConfigDataApplicationContextInitializer.class)
class MyConfigFileTests {
// ...
}
import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer
import org.springframework.test.context.ContextConfiguration
@ContextConfiguration(classes = [Config::class], initializers = [ConfigDataApplicationContextInitializer::class])
class MyConfigFileTests {
// ...
}
单独使用 ConfigDataApplicationContextInitializer 并不提供对 @Value("${…}")
注入的支持。它的唯一作用是确保 application.properties
文件被加载到 Spring 的 Environment 中。为了支持 @Value,你需要额外配置一个 PropertySourcesPlaceholderConfigurer,或者使用 @SpringBootTest,它会自动为你配置一个。
测试属性值
TestPropertyValues 允许你快速将属性添加到 ConfigurableEnvironment 或 ConfigurableApplicationContext 中。你可以使用 key=value
字符串来调用它,如下所示:
- Java
- Kotlin
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.mock.env.MockEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
class MyEnvironmentTests {
@Test
void testPropertySources() {
MockEnvironment environment = new MockEnvironment();
TestPropertyValues.of("org=Spring", "name=Boot").applyTo(environment);
assertThat(environment.getProperty("name")).isEqualTo("Boot");
}
}
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.boot.test.util.TestPropertyValues
import org.springframework.mock.env.MockEnvironment
class MyEnvironmentTests {
@Test
fun testPropertySources() {
val environment = MockEnvironment()
TestPropertyValues.of("org=Spring", "name=Boot").applyTo(environment)
assertThat(environment.getProperty("name")).isEqualTo("Boot")
}
}
OutputCaptureExtension
OutputCaptureExtension 是一个 JUnit Extension,你可以使用它来捕获 System.out 和 System.err 的输出。要使用它,请添加 @ExtendWith(OutputCaptureExtension.class)
,并将 CapturedOutput 作为参数注入到测试类的构造函数或测试方法中,如下所示:
- Java
- Kotlin
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(OutputCaptureExtension.class)
class MyOutputCaptureTests {
@Test
void testName(CapturedOutput output) {
System.out.println("Hello World!");
assertThat(output).contains("World");
}
}
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.boot.test.system.CapturedOutput
import org.springframework.boot.test.system.OutputCaptureExtension
@ExtendWith(OutputCaptureExtension::class)
class MyOutputCaptureTests {
@Test
fun testName(output: CapturedOutput?) {
println("Hello World!")
assertThat(output).contains("World")
}
}
TestRestTemplate
TestRestTemplate 是 Spring RestTemplate 的一个便捷替代品,在集成测试中非常有用。你可以获取一个普通的模板,或者一个发送基本 HTTP 认证(带有用户名和密码)的模板。无论是哪种情况,该模板都是容错的。这意味着它以测试友好的方式运行,不会在 4xx 和 5xx 错误时抛出异常。相反,这些错误可以通过返回的 ResponseEntity 及其状态码来检测。
Spring Framework 5.0 提供了一个新的 WebTestClient,它适用于 WebFlux 集成测试 以及 WebFlux 和 MVC 端到端测试。与 TestRestTemplate 不同,它提供了一个流畅的 API 用于断言。
建议但不强制使用 Apache HTTP 客户端(版本 5.1 或更高)。如果你的类路径中包含该客户端,TestRestTemplate 会通过适当配置客户端来响应。如果你确实使用了 Apache HTTP 客户端,将启用一些额外的对测试友好的功能:
-
重定向不会被跟踪(因此你可以断言响应的位置)。
-
Cookie 被忽略(因此模板是无状态的)。
TestRestTemplate 可以直接在你的集成测试中实例化,如下例所示:
- Java
- Kotlin
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import static org.assertj.core.api.Assertions.assertThat;
class MyTests {
private final TestRestTemplate template = new TestRestTemplate();
@Test
void testRequest() {
ResponseEntity<String> headers = this.template.getForEntity("https://myhost.example.com/example", String.class);
assertThat(headers.getHeaders().getLocation()).hasHost("other.example.com");
}
}
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.boot.test.web.client.TestRestTemplate
class MyTests {
private val template = TestRestTemplate()
@Test
fun testRequest() {
val headers = template.getForEntity("https://myhost.example.com/example", String::class.java)
assertThat(headers.headers.location).hasHost("other.example.com")
}
}
或者,如果你使用 @SpringBootTest 注解并指定 WebEnvironment.RANDOM_PORT
或 WebEnvironment.DEFINED_PORT
,你可以注入一个完全配置好的 TestRestTemplate 并开始使用它。如果需要,可以通过 RestTemplateBuilder bean 应用额外的自定义配置。任何未指定主机和端口的 URL 都会自动连接到嵌入式服务器,如下例所示:
- Java
- Kotlin
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class MySpringBootTests {
@Autowired
private TestRestTemplate template;
@Test
void testRequest() {
HttpHeaders headers = this.template.getForEntity("/example", String.class).getHeaders();
assertThat(headers.getLocation()).hasHost("other.example.com");
}
@TestConfiguration(proxyBeanMethods = false)
static class RestTemplateBuilderConfiguration {
@Bean
RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder().connectTimeout(Duration.ofSeconds(1)).readTimeout(Duration.ofSeconds(1));
}
}
}
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.context.annotation.Bean
import java.time.Duration
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class MySpringBootTests(@Autowired val template: TestRestTemplate) {
@Test
fun testRequest() {
val headers = template.getForEntity("/example", String::class.java).headers
assertThat(headers.location).hasHost("other.example.com")
}
@TestConfiguration(proxyBeanMethods = false)
internal class RestTemplateBuilderConfiguration {
@Bean
fun restTemplateBuilder(): RestTemplateBuilder {
return RestTemplateBuilder().connectTimeout(Duration.ofSeconds(1))
.readTimeout(Duration.ofSeconds(1))
}
}
}