1

I use the SpringJUnit4ClassRunner to run integration tests for a Spring Boot application.

During my search I found out it is possible to reload the app context with @DirtiesContext.

My issue: I only need to reload the security configuration (which depends on a DB entry), while keeping the rest as is (or to be precise: I need to keep the H2 database as is).

How to only reload the security configuration before a JUnit test?

Pawel Os.
  • 611
  • 8
  • 26

2 Answers2

1

If you need to keep H2 Database as it is, you might consider setting the property spring.jpa.hibernate.ddl-auto to update, because it will create the database if doesn't exists and will keep it the existing if exists. If you have already have a application-test.properties you can create another properties like application-securityTest.properties.

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

Then in your test class you need to activate this profile with the annotation @ActiveProfiles and use the @DirtiesContext to reload Spring context:

@ActiveProfiles("securityTest")
@DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD)
public class SecurityTest { ... }
Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37
  • I am using Liquibase, forgot to mention. Or another approach: how to insert data (it is only one record which is needed for the startup of the Boot application) into the DB before Spring Boot starts loading the application context? – Pawel Os. Aug 02 '17 at 07:57
  • 1
    You can do this: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html or you can write an SQL script with your insert statement and execute it (https://stackoverflow.com/a/1497614/4857050) before the test execution – Raphael Amoedo Aug 02 '17 at 14:06
1

I solved the problem another way, I modified the implemention so that the security configuration can variably be modified during runtime and doesn't require the DB entry at startup.

Pawel Os.
  • 611
  • 8
  • 26