一些在测试应用程序时通常有用的测试实用程序类打包为 .spring-bootSpring中文文档

ConfigDataApplicationContextInitializer

ConfigDataApplicationContextInitializer是可以应用于测试以加载 Spring Boot 文件的。 当您不需要 提供的全套功能时,可以使用它,如以下示例所示:ApplicationContextInitializerapplication.properties@SpringBootTestSpring中文文档

import org.springframework.boot.test.context.ConfigDataApplicationContextInitializer;
import org.springframework.test.context.ContextConfiguration;

@ContextConfiguration(classes = Config.class, initializers = ConfigDataApplicationContextInitializer.class)
class MyConfigFileTests {

	// ...

}
单独使用不支持注射。 它唯一的工作是确保文件被加载到 Spring 的 . 为了获得支持,您需要另外配置一个或使用 ,它会自动为您配置一个。ConfigDataApplicationContextInitializer@Value("${…​}")application.propertiesEnvironment@ValuePropertySourcesPlaceholderConfigurer@SpringBootTest
单独使用不支持注射。 它唯一的工作是确保文件被加载到 Spring 的 . 为了获得支持,您需要另外配置一个或使用 ,它会自动为您配置一个。ConfigDataApplicationContextInitializer@Value("${…​}")application.propertiesEnvironment@ValuePropertySourcesPlaceholderConfigurer@SpringBootTest

TestPropertyValues

TestPropertyValues允许您快速向 或 添加属性。 您可以使用字符串调用它,如下所示:ConfigurableEnvironmentConfigurableApplicationContextkey=valueSpring中文文档

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

}

输出捕获

OutputCapture是可用于捕获和输出的 JUnit。 若要使用它,请将参数添加并注入到测试类构造函数或测试方法中,如下所示:ExtensionSystem.outSystem.err@ExtendWith(OutputCaptureExtension.class)CapturedOutputSpring中文文档

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

}

TestRest模板

TestRestTemplate是 Spring 的便捷替代品,在集成测试中很有用。 您可以获取普通模板或发送基本 HTTP 身份验证(使用用户名和密码)的模板。 无论哪种情况,模板都是容错的。 这意味着它以测试友好的方式运行,不会对 4xx 和 5xx 错误抛出异常。 相反,可以通过返回的及其状态代码来检测此类错误。RestTemplateResponseEntitySpring中文文档

Spring Framework 5.0 提供了一个适用于 WebFlux 集成测试以及 WebFlux 和 MVC 端到端测试的新功能。 它为断言提供了流畅的 API,这与 .WebTestClientTestRestTemplate

建议(但不是强制性的)使用 Apache HTTP 客户端(版本 5.1 或更高版本)。 如果您的类路径上有它,则通过适当配置客户端来响应。 如果您确实使用 Apache 的 HTTP 客户端,则会启用一些额外的测试友好功能:TestRestTemplateSpring中文文档

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

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

}

或者,如果将注释与 或 一起使用,则可以注入完全配置并开始使用它。 如有必要,可以通过 Bean 应用其他自定义项。 任何未指定主机和端口的 URL 都会自动连接到嵌入式服务器,如以下示例所示:@SpringBootTestWebEnvironment.RANDOM_PORTWebEnvironment.DEFINED_PORTTestRestTemplateRestTemplateBuilderSpring中文文档

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().setConnectTimeout(Duration.ofSeconds(1))
				.setReadTimeout(Duration.ofSeconds(1));
		}

	}

}
Spring Framework 5.0 提供了一个适用于 WebFlux 集成测试以及 WebFlux 和 MVC 端到端测试的新功能。 它为断言提供了流畅的 API,这与 .WebTestClientTestRestTemplate