【问题标题】:JUnit 4 & Spring Boot - selectively reload context/reload Spring Security configuration before testJUnit 4 & Spring Boot - 在测试前有选择地重新加载上下文/重新加载 Spring Security 配置
【发布时间】:2018-01-08 12:59:49
【问题描述】:

我使用 SpringJUnit4ClassRunner 为 Spring Boot 应用程序运行集成测试。

在搜索过程中,我发现可以使用 @DirtiesContext 重新加载应用上下文。

我的问题:我只需要重新加载安全配置(这取决于数据库条目),而其余部分保持不变(或者准确地说:我需要保持 H2 数据库不变)。

如何在 JUnit 测试之前只重新加载安全配置?

【问题讨论】:

    标签: spring-boot junit spring-security junit4 applicationcontext


    【解决方案1】:

    如果您需要保持 H2 数据库原样,您可以考虑将属性 spring.jpa.hibernate.ddl-auto 设置为 update,因为如果数据库不存在,它将创建数据库,如果存在,它将保持现有数据库。如果您已经有一个application-test.properties,您可以创建另一个属性,例如application-securityTest.properties

    #... Your DB connection info
    spring.jpa.hibernate.ddl-auto=update
    

    然后在您的测试类中,您需要使用注释@ActiveProfiles 激活此配置文件并使用@DirtiesContext 重新加载Spring 上下文:

    @ActiveProfiles("securityTest")
    @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
    public class SecurityTest { ... }
    

    【讨论】:

    【解决方案2】:

    我用另一种方式解决了这个问题,我修改了实现,以便可以在运行时可变地修改安全配置,并且在启动时不需要数据库条目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-12
      • 2019-04-26
      • 2021-10-20
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 2014-09-11
      相关资源
      最近更新 更多