欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot单元测试

程序员文章站 2022-04-26 09:17:57
...

在测试类中读取某个application-开头的propertiesyaml中的属性

命名规则

  • 必须以application-开头
    • application-dev.properties
    • application-test.properties
    • application-dev.yml
    • application-dev.yml

通过@ActiveProfiles来指定使用哪个文件

例子

package com.atgenee.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
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("test") //指定使用application-test.yml
public class TestApplicationTests {

    @Value("${user.first-name}")
    private String firstName;

    @Value("${user.weight}")
    private Integer weight;

    @Test
    public void hei() {
        System.out.println(firstName);
        System.out.println(weight);
    }

}

@TestPropertySource

  • 加载指定配置文件
  • 可以是properties文件,也可以是yaml

例子

package com.atgenee.demo;

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.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = { "spring.config.location = classpath:test.properties" })
public class TestApplicationTests {

    @Value("${user.first-name}")
    private String firstName;

    @Value("${user.weight}")
    private Integer weight;

    @Test
    public void hei() {
        System.out.println(firstName);
        System.out.println(weight);
    }

}