我想用JUnit和Spring创建2个测试用例,它需要相同的类路径资源 batch-configuration.properties ,但此文件的内容因测试而异。
实际上在我的maven项目中,我创建了这些文件树:
但是如何根据我的测试用例定义我的根类路径(使用ExtractionBatchConfiguration
在classpath:batch-configuration.properties
中加载文件)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ExtractionBatchConfiguration.class }, loader = AnnotationConfigContextLoader.class)
@PropertySource("classpath:test1/batch-configuration.properties") // does not override ExtractionBatchConfiguration declaration
public class ExtractBatchTestCase {
private static ConfigurableApplicationContext context;
private JobLauncherTestUtils jobLauncherTestUtils;
@BeforeClass
public static void beforeClass() {
context = SpringApplication.run(ExtractionBatchConfiguration.class);
}
@Before
public void setup() throws Exception {
jobLauncherTestUtils = new JobLauncherTestUtils();
jobLauncherTestUtils.setJobLauncher(context.getBean(JobLauncher.class));
jobLauncherTestUtils.setJobRepository(context.getBean(JobRepository.class));
}
@Test
public void testGeneratedFiles() throws Exception {
jobLauncherTestUtils.setJob(context.getBean("extractJob1", Job.class));
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
Assert.assertNotNull(jobExecution);
Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
// ... other assert
}
}
配置:
@Configuration
@EnableAutoConfiguration
@PropertySources({
@PropertySource("batch-default-configuration.properties"),
@PropertySource("batch-configuration.properties")
})
public class ExtractionBatchConfiguration { /* ... */ }
我使用的是Spring 4.0.9(我不能使用4.1.x)和JUnit 4.11
编辑:
使用hzpz建议的自定义ApplicationContextInitializer覆盖解决某些问题的属性位置(application.properties + batch-configuration.properties)后,我遇到了@ConfigurationProperties的另一个问题:
@ConfigurationProperties(prefix = "spring.ldap.contextsource"/*, locations = "application.properties"*/)
public class LdapSourceProperties {
String url;
String userDn;
String password;
/* getters, setters */
}
和配置:
@Configuration
@EnableConfigurationProperties(LdapSourceProperties.class)
public class LdapConfiguration {
@Bean
public ContextSource contextSource(LdapSourceProperties properties) {
LdapContextSource contextSource = new LdapContextSource();
contextSource.setUrl(properties.getUrl());
contextSource.setUserDn(properties.getUserDn());
contextSource.setPassword(properties.getPassword());
return contextSource;
}
}
创建ContextSource时,所有LdapSourceProperties的字段都为空,但如果我取消注释locations = "application.properties"
,则只有当application.properties位于根类路径中时,它才有效。 @ConfigurationProperties使用的默认环境似乎不包含嵌套属性...
替代解决方案:
最后,我将所有属性放入application-<profile>.properties
个文件中(并删除@PropertySource定义)。我现在可以使用application-test1.properties
和application-test2.properties
。在我的测试类中,我可以设置@ActiveProfiles("test1")
来激活配置文件并加载相关属性。
答案 0 :(得分:1)
首先,您需要了解JUnit如何使用Spring进行测试。 SpringJUnit4ClassRunner
的目的是为您创建ApplicationContext
(使用@ContextConfiguration
)。您不需要自己创建上下文。
如果正确设置了上下文,则可以使用@Autowired
来获取测试中所需的依赖项。 ExtractBatchTestCase
应该是这样的:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ExtractionBatchConfiguration.class })
public class ExtractBatchTestCase {
@Autowired
private JobLauncher jobLauncher;
@Autowired
private JobRepository jobRepository;
@Autowired
@Qualifier("extractJob1")
private Job job;
private JobLauncherTestUtils jobLauncherTestUtils;
@Before
public void setup() throws Exception {
jobLauncherTestUtils = new JobLauncherTestUtils();
jobLauncherTestUtils.setJobLauncher(jobLauncher);
jobLauncherTestUtils.setJobRepository(jobRepository);
}
@Test
public void testGeneratedFiles() throws Exception {
jobLauncherTestUtils.setJob(job);
JobExecution jobExecution = jobLauncherTestUtils.launchJob();
Assert.assertNotNull(jobExecution);
Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
// ... other assert
}
}
其次,@ProperySource
状态为Javadoc:
如果给定的属性键存在于多个.properties文件中,则处理的最后一个
@PropertySource
注释将“赢”并覆盖。 [...]在某些情况下,使用
@ProperySource
注释时严格控制属性源顺序可能是不可能或不切实际的。例如,如果@Configuration
类[...]是通过组件扫描注册的,则排序很难预测。在这种情况下 - 如果覆盖很重要 - 建议用户回退使用编程的PropertySource API。
为您的测试创建ApplicationContextInitializer
,以添加一些具有最高搜索优先级的测试属性,这些属性将始终为“赢”:
public class MockApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
MutablePropertySources propertySources = applicationContext.getEnvironment().getPropertySources();
MockPropertySource mockEnvVars = new MockPropertySource().withProperty("foo", "bar");
propertySources.addFirst(mockEnvVars);
}
}
使用@ContextConfiguration
声明它:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ExtractionBatchConfiguration.class },
initializers = MockApplicationContextInitializer.class)
public class ExtractBatchTestCase {
// ...
}