测试工具
一些在测试应用程序时通常有用的测试工具类被打包为 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
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
的一个便捷替代品,在集成测试中很有用。
您可以获取一个普通模板或一个发送Basic HTTP认证(带用户名和密码)的模板。
在这两种情况下,模板都是容错的。
这意味着它以测试友好的方式运行,不会在4xx和5xx错误时抛出异常。
相反,可以通过返回的 ResponseEntity
及其状态码来检测此类错误。
提示:Spring Framework 5.0提供了一个新的 WebTestClient
,它适用于 WebFlux集成测试和 WebFlux和MVC端到端测试。
与 TestRestTemplate
不同,它提供了用于断言的流式API。
建议(但不是强制)使用Apache HTTP Client(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")
}
}
或者,如果您使用带有 WebEnvironment.RANDOM_PORT
或 WebEnvironment.DEFINED_PORT
的 @SpringBootTest
注解,您可以注入一个完全配置的 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))
}
}
}