如何在Spring Test中注册ApplicationEnvironmentPreparedEvent [英] How to register a ApplicationEnvironmentPreparedEvent in Spring Test
问题描述
我有一个@SpringBootTest
,并且我需要通过ApplicationEnvironmentPreparedEvent
通知以创建数据库文件(如果该文件不存在),因为我的应用程序数据库尝试连接到该文件并且该文件不存在.
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.
我是通过SpringApplicationBuilder
来执行此操作的,但是在JUnit中,我无法访问此构建器.这是我当前的main
代码:
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);
}
}
}
});
Enviroment
准备就绪时如何通知我,以便在配置数据源之前读取JDBC URL并创建用于测试的数据库文件?
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?
推荐答案
由于在测试中主方法未运行,因此您的监听器在测试中不可用的原因.
首先,您需要提取该类的侦听器,以供将来在测试中使用(例如MyListener
).
第二次使用自定义加载程序在应用程序中声明监听器.
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;
}
}
这篇关于如何在Spring Test中注册ApplicationEnvironmentPreparedEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!