DEV Community

Thomas
Thomas

Posted on

Test ApplicationReadyEvent in Spring boot

I had a migration feature to write and that had to run every time the application started. I will only have to do it once, but idempotent code will be for another time.

Code that will run on initialization of the application is pretty easy in Spring. Annotate a method in a discoverable bean with @EventListener(ApplicationReadyEvent.class) and you good to go.

`
@Component
public class FutonMigrationBean {
private static boolean migrationFinished = false;

public FutonMigrationBean() {
}

@EventListener(ApplicationReadyEvent.class)
public void migrateFuton() throws Exception {
    //some migration code

    migrationFinished = true;
}

public static boolean isMigrationFinished() {
    return migrationFinished;
}
Enter fullscreen mode Exit fullscreen mode

}
`

It doesn't have to be for only Application event instances, you can become as creative as you want.

But how do we know this code will keep running on startup

We have to write a test that verifies the implementation of the code, but if we require this code to run on startup, we also have be sure that keeps on happening.

For that we have a spring boot test. In my implementation, I have hidden everything besides the boolean 'migrationFinished'. The boolean is initialized as 'false', so if it's true, we know that the code has ran.

`
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { SpringTestConfiguration.class })
class FutonMigrationOnStartUpTest {

@Test
void verifyMigrationOnStartUp() {
    Assertions.assertThat(FutonMigrationBean.isMigrationFinished()).isTrue();
}
Enter fullscreen mode Exit fullscreen mode

}
`

Because it's a little overkill to use springboot test and load the entire context, we limit ourselves to a small config that contains what we need inside SpringTestConfiguration.class

`
@Configuration
@ComponentScan("be.inbo.inboveg.mobile.migration")
public class SpringTestConfiguration {;

@Bean(initMethod="migrateFuton")
public FutonMigrationBean futonMigrationBean(){};
Enter fullscreen mode Exit fullscreen mode

}
`

It is a configuration of our Spring context, that's why we need @Configuration annotation. We provide that bean that we need with the class that has to be executed when initialized.

Now when we run our test, the migration function will be executed.

Happy testing

Side note - this is my first post, if you had doubts, questions, feedback, always welcome

Top comments (0)