一、项目准备

1.创建项目

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

2.配置yml文件

test:
  name: FOREVER
  love: 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;
    @Test
    void contextLoads() {
        System.out.println(name);
    }

}

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

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;
    @Test
    void contextLoads() {
        System.out.println(name);
    }

}

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

 

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;
    @Test
    void 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 {
    //开发误用
    @Bean
    public 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 {
    @Autowired
    private String msg;

    @Test
    void contextLoads() {
        System.out.println(msg);
    }

}

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

11-09 00:25