可以在运行基于Spring Boot的测试的测试类上指定的注释。在常规的Spring TestContext框架之上提供了以下特性:
-
默认提供SpringBootContextLoader作为ContextLoader,也通过 @ContextConfiguration(loader=…)来自定义
-
若没有显示指定,将查找嵌套的@Configuration类,然后返回到SpringBootConfiguration搜索配置
-
允许使用properties属性定义自定义环境属性。
-
允许使用args属性定义应用程序参数。
-
支持不同webEnvironment模式,包括自定义运行web服务器监听或默认为随机端口
-
web服务模式下,自动注册一个TestRestTemplate和/或WebTestClient bean用于web测试
| 配置名称 | 备注 |
|---|---|
| value | 配置属性 |
| properties | 配置属性 |
| args | 应用启动参数 |
| classes | 指定加载容器上下文配置类,等同于@ContextConfiguration中的class,若没有显示指定,将查找嵌套的@Configuration类,然后返回到SpringBootConfiguration搜索配置 |
关于 aliasFor可以参考 spring 官方
SpringBootTest源码@Target(ElementType.TYPE)//注解只能用于Class, interface (including annotation type), or enum declaration
@Retention(RetentionPolicy.RUNTIME)//注释将由编译器记录在类文件中,并在运行时由VM保留,因此可以反射性地读取它们。
@documented
@Inherited //允许子类继承
@BootstrapWith(SpringBootTestContextBootstrapper.class)
@ExtendWith(SpringExtension.class)
public @interface SpringBootTest {
@AliasFor("properties")
String[] value() default {};
@AliasFor("value")
String[] properties() default {};
String[] args() default {};
Class>[] classes() default {};
WebEnvironment webEnvironment() default WebEnvironment.MOCK;
enum WebEnvironment {
MOCK(false),
RANDOM_PORT(true),
DEFINED_PORT(true),
NONE(false);
private final boolean embedded;
WebEnvironment(boolean embedded) {
this.embedded = embedded;
}
public boolean isEmbedded() {
return this.embedded;
}
}
}
demo案例
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = "server.port=8081", args = "--spring.application.name=demoTest",
classes = AppApplication.class)
@import(MyConfig.class)
public class SpringBootDemoTest {
@Autowired
private ApplicationContext applicationContext;
@Value("${spring.application.name}")
private String appName;
@Autowired(required = false)
private MyConfig myConfig;
@Test
void AppApplicationTest() {
assert ("demoTest".equals(appName));
assertThat(myConfig).isNotNull().extracting("cfgName").isEqualTo("11");
assertThat(applicationContext).isNotNull();
}
}
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class MyConfig {
private String cfgName = "11";
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AppApplication {
public static void main(String[] args) {
SpringApplication.run(AppApplication.class, args);
}
}



