SpringBoot单元测试

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

命名规则

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

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

例子

  1. package com.atgenee.demo;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.test.context.ActiveProfiles;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. @RunWith(SpringRunner.class)
  10. @SpringBootTest
  11. @ActiveProfiles("test") //指定使用application-test.yml
  12. public class TestApplicationTests {
  13. @Value("${user.first-name}")
  14. private String firstName;
  15. @Value("${user.weight}")
  16. private Integer weight;
  17. @Test
  18. public void hei() {
  19. System.out.println(firstName);
  20. System.out.println(weight);
  21. }
  22. }

@TestPropertySource

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

例子

  1. package com.atgenee.demo;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.TestPropertySource;
  7. import org.springframework.test.context.junit4.SpringRunner;
  8. @RunWith(SpringRunner.class)
  9. @SpringBootTest
  10. @TestPropertySource(properties = { "spring.config.location = classpath:test.properties" })
  11. public class TestApplicationTests {
  12. @Value("${user.first-name}")
  13. private String firstName;
  14. @Value("${user.weight}")
  15. private Integer weight;
  16. @Test
  17. public void hei() {
  18. System.out.println(firstName);
  19. System.out.println(weight);
  20. }
  21. }

0
0
0

添加评论

正在回复:
取消
0
0
0
0