How to register a ApplicationEnvironmentPreparedEvent in Spring Test

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-02 09:51:11

问题


I have a @SpringBootTest and I need to notified via ApplicationEnvironmentPreparedEvent to create a database file if it not exists, because my application database tries to connect to it and it doesn't exists.

I was doing this via SpringApplicationBuilder, but in the JUnit I haven't access to this builder. This my current main code:

SpringApplicationBuilder appBuilder = new SpringApplicationBuilder();
appBuilder.headless(false);
appBuilder.listeners(new ApplicationListener<ApplicationEvent>() {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            Environment env = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment();
            String datasourceUrl = env.getProperty(RepositoryConfig.JDBC_URL_PROPERTY);

            File db = FirebirdUtil.extractDatabaseFile(datasourceUrl);
            if (db != null) {
                String user = env.getProperty(RepositoryConfig.JDBC_USER_PROPERTY);
                String password = env.getProperty(RepositoryConfig.JDBC_PASSWORD_PROPERTY);

                // this will create the FDB file if it doesn't exists
                FirebirdUtil.createDatabaseifNotExists(db, user, password);
            }
        }
    }
});

How can I be notified when the Enviroment is ready, to read the JDBC URL and create the database file for the test before the datasource configuration?


回答1:


Because in test the main method did not run, that why your listeners are not available in the Test.
First you needs extract listener to the class for future using in test (for exmpl. MyListener).
Second using custom loader for declare listeners in the application.

I just check it works for me. That is example for test:

@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(loader = CustomLoader.class)
public class DemoApplicationTests {

public static class CustomLoader extends SpringBootContextLoader {

    @Override
    protected SpringApplication getSpringApplication() {
        SpringApplication app = super.getSpringApplication();
        app.addListeners(new MyListener());
        return app;
    }
}


来源:https://stackoverflow.com/questions/52085355/how-to-register-a-applicationenvironmentpreparedevent-in-spring-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!