跳到主要内容
版本:3.5.10

Test Utilities

QWen Max 中英对照 Test Utilities

一些在测试应用程序时通常很有用的测试工具类被打包在 spring-boot 中。

ConfigDataApplicationContextInitializer

ConfigDataApplicationContextInitializer 是一个 ApplicationContextInitializer,你可以将其应用于测试中,以加载 Spring Boot 的 application.properties 文件。当你不需要 @SpringBootTest 提供的完整功能集时,可以使用它,如下例所示:

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 可让你快速向 ConfigurableEnvironmentConfigurableApplicationContext 添加属性。你可以使用 key=value 字符串调用它,如下所示:

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");
}

}

OutputCaptureExtension

OutputCaptureExtension 是一个 JUnit Extension,可用于捕获 System.outSystem.err 的输出。要使用它,请添加 @ExtendWith(OutputCaptureExtension.class),并将 CapturedOutput 作为参数注入到你的测试类构造函数或测试方法中,如下所示:

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");
}

}

TestRestTemplate

TestRestTemplate 是 Spring 的 RestTemplate 在集成测试中的一种便捷替代方案。你可以获取一个普通的模板,也可以获取一个发送 Basic HTTP 认证(带用户名和密码)的模板。无论哪种情况,该模板都具有容错性。这意味着它在测试中表现得更加友好:当遇到 4xx 和 5xx 错误时不会抛出异常,而是可以通过返回的 ResponseEntity 及其状态码来检测这些错误。

提示

Spring Framework 5.0 提供了一个新的 WebTestClient,可用于 WebFlux 集成测试以及 WebFlux 和 MVC 的端到端测试。它提供了一套流畅的 API 用于断言,这与 TestRestTemplate 不同。

建议(但非强制)使用 Apache HTTP Client(版本 5.1 或更高)。如果你的 classpath 中包含该客户端,TestRestTemplate 会自动对其进行适当配置。如果你确实使用了 Apache 的 HTTP 客户端,它会被配置为忽略 Cookie(从而使模板保持无状态)。

TestRestTemplate 可以在你的集成测试中直接实例化,如下例所示:

import org.junit.jupiter.api.Test;

import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
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> response = this.template.getForEntity("https://myhost.example.com/example",
String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
// Other assertions to verify the response
}

}

或者,如果你使用 @SpringBootTest 注解并配合 WebEnvironment.RANDOM_PORTWebEnvironment.DEFINED_PORT,你可以注入一个完全配置好的 TestRestTemplate 并直接使用它。如有必要,还可以通过 RestTemplateBuilder Bean 进行额外的自定义配置。任何未指定主机和端口的 URL 会自动连接到内嵌服务器,如下例所示:

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.HttpStatus;
import org.springframework.http.ResponseEntity;

import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class MySpringBootTests {

@Autowired
private TestRestTemplate template;

@Test
void testRequest() {
ResponseEntity<String> response = this.template.getForEntity("/example", String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
// Other assertions to verify the response
}

@TestConfiguration(proxyBeanMethods = false)
static class RestTemplateBuilderConfiguration {

@Bean
RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder().connectTimeout(Duration.ofSeconds(1)).readTimeout(Duration.ofSeconds(1));
}

}

}