栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBootTest注解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBootTest注解

@SpringBootTest注解 --基于SpringBoot2.5.7版本 SpringBootTest介绍

可以在运行基于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);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/631995.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号