【问题标题】:Spring boot unit test how to load filesSpring Boot 单元测试如何加载文件
【发布时间】:2020-06-24 07:29:52
【问题描述】:

大家。我在写junit的时候发现@ActiveProfiles对应我的资源目录。 不明白spring boot是怎么加载资源文件的,为什么不指定@ActiveProfiles默认读取哪个应用程序文件?

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
@ActiveProfiles("test")
public class NewTutorGroupIaoTest {
}
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = Application.class)
@ActiveProfiles("test")
public class NewTutorGroupIaoTest {
}

项目目录:

project 
- src 
    - main
        - java
        - resource
    - test
        - java
        - resource

【问题讨论】:

    标签: java spring spring-boot junit


    【解决方案1】:

    如果您使用@Profile("test") 标记类,则可以通过激活test 配置文件来确保它们已加载(到ApplicationContext) - 使用@ActiveProfiles("test")spring.profiles.active=test 或其他多种方式.可以使用@Profile("!test") 排除类

    更多详情:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-profiles

    此外,通过激活配置文件,您还可以激活要拾取的属性文件...您的项目中可能还有以下文件:

    • application.properties
    • application-default.properties
    • application-test.properties

    如果您同时存在application.propertiesapplication-test.properties,则application.properties 构成基本配置,application-test.properties 将覆盖任何现有属性,并且还可能提供其他配置值。

    如果您提供/指定 no 配置文件,则会激活 default 配置文件。这将导致 application.properties + application-default.properties 被合并(和以前一样)。

    您将在日志中看到哪个配置文件在 Spring 日志输出的开头附近被激活。

    【讨论】:

    • 谢谢!之前生病了,没看资料,不好意思。我看到了文档的 Profile 和 ActiveProfiles 。并且我也看了SpringBootTest源码,明白了这个问题,非常感谢
    猜你喜欢
    • 2020-01-02
    • 2017-02-12
    • 2015-11-06
    • 2016-05-28
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多