问题:从maven(mvn verify)运行集成测试时,Spring应用程序上下文没有正确初始化,它没有考虑我的自定义ApplicationContextInitializer类。
测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {MainApplication.class}, initializers = CustomContextInitializer.class)
@WebIntegrationTest
public class ApplicationIT {
// Running a SOAPUI suite as a JUnit Test
@Test
public void TestGateway() throws Exception {
SoapUITestCaseRunner runner = new SoapUITestCaseRunner();
runner.setProjectFile("../gateway/src/test/resources/soapui/gateway-soapui.xml");
runner.run();
}
}
MainApplication类:
@Configuration
@ComponentScan(basePackages = {
// different packages here (not relevant)
})
@EnableAutoConfiguration
public class MainApplication {
public static void main(String[] args) throws Exception {
new SpringApplicationBuilder(MainApplication.class)
.initializers(new CustomContextInitializer())
.run(args);
}
}
CustomContextInitiliazer类(用于将自定义 .properties 文件添加到spring环境应用程序上下文中):
public class CustomContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>{
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment env = applicationContext.getEnvironment();
try {
Resource[] res = new PathMatchingResourcePatternResolver().getResources("classpath*:/*.properties");
for (Resource re : res) {
env.getPropertySources().addFirst(new ResourcePropertySource(re));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果:
1)当我启动并运行应用程序时(从IDE或通过调用mvn exec),一切正常。
2)从IDE启动时,集成测试运行正常。
3)通过 maven verify 调用时,集成测试会抛出错误,因为自定义属性文件未加载到spring上下文环境中。结果就像我在测试类中没有编写 initializers = CustomContextInitializer.class 一样,并尝试从IDE运行测试。
答案 0 :(得分:0)
我认为您的代码是正确的,但您的.properties
文件可能位于错误的位置。确保它们位于<project>/src/main/resources
之下,或者您已在maven中配置了自定义资源文件夹。如果它们位于<project>/src/main/java
之下,就maven而言,它们将不会成为类路径的一部分。