SpringBoot加载测试类属性和配置说明

编程入门 行业动态 更新时间:2024-10-27 16:28:37

SpringBoot<a href=https://www.elefans.com/category/jswz/34/1771433.html style=加载测试类属性和配置说明"/>

SpringBoot加载测试类属性和配置说明

一、项目准备

1.创建项目

2.配置yml文件

test:name: FOREVERlove: sing

 二、测试类属性

1.@Value

说明:读取yml中的数据。

package com.forever;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class Springboot10TestApplicationTests {@Value("${test.name}")private  String name;@Testvoid contextLoads() {System.out.println(name);}}

2.@SpringBootTest

说明:@SpringBootTest(properties = "test.name=Good");单文件临时生效。@SpringBootTest(args = {"--test.name=Better"})

package com.forever;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest(properties = "test.name=Good")
class Springboot10TestApplicationTests {@Value("${test.name}")private  String name;@Testvoid contextLoads() {System.out.println(name);}}

 

 

package com.forever;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest(args = {"--test.name=Better"})
class Springboot10TestApplicationTests {@Value("${test.name}")private  String name;@Testvoid contextLoads() {System.out.println(name);}}
 
@SpringBootTest(properties = {"test.name=Good"},args = {"--test.name=Better"})

说明:命令行的优先级高于其他的;args覆盖properties。

 三、测试类配置

1.@Import

说明:导入配置类,@Import(MsgConfig.class)。

1.1创建配置类

说明:开发中,不能将方法通过@Bean变成bean类。

package com.forever.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MsgConfig {//开发误用@Beanpublic String msg(){return "bean msg";}
}

1.2测试类

说明:通过@Import追加配置。

package com.forever;import com.forever.config.MsgConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;@SpringBootTest
//追加了配置
@Import(MsgConfig.class)
class Springboot10TestApplicationTests {@Autowiredprivate String msg;@Testvoid contextLoads() {System.out.println(msg);}}

更多推荐

SpringBoot加载测试类属性和配置说明

本文发布于:2023-11-15 21:55:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606946.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   测试   类属   SpringBoot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!