junit测试类获取springboot的yml配置文件参数

1.类上增加注解

@RunWith(SpringRunner.class)
@SpringBootTest()

2.获取配置参数值注解

    @Value("${pay.mid}")
    private String mid;

测试效果

  • application.yml文件
pay:
  mid: 123456
  •  junit测试类
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest()
public class DemoJunitTest {
    @Value("${pay.mid}")
    private String mid;

    @Test
    public void getPayMid() {
        System.out.println("mid->"+mid);
    }
}
  • 运行结果 

 3.获取指定配置文件的参数,例如获取application-dev.yml

  • 测试类多增加个注解
@ActiveProfiles("dev")
  •  application-dev.yml配置文件内容
pay:
  mid: 654321
  •  junit测试类
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest()
@ActiveProfiles("dev")
public class DemoJunitTest {
    @Value("${pay.mid}")
    private String mid;

    @Test
    public void getPayMid() {
        System.out.println("mid->"+mid);
    }
}
  • 运行结果 

你可能感兴趣的:(java,java,spring,boot,spring)