如何在单元测试中设置不同的类路径以使用Spring加载资源

Aur*_*e77 7 java spring unit-testing spring-batch spring-boot

我想使用 JUnit 和 Spring 创建 2 个测试用例,它们需要相同的类路径资源batch-configuration.properties,但该文件的内容根据测试而有所不同。

实际上在我的 Maven 项目中,我创建了这些文件树:

  • src/test/resources/test1/batch-configuration.properties
  • src/test/resources/test2/batch-configuration.properties

但是我如何根据我的测试用例定义我的根类路径(文件是在ExtractionBatchConfigurationusing中加载的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
    }

}
Run Code Online (Sandbox Code Playgroud)

配置:

@Configuration
@EnableAutoConfiguration
@PropertySources({
    @PropertySource("batch-default-configuration.properties"),
    @PropertySource("batch-configuration.properties")
})
public class ExtractionBatchConfiguration { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

我正在使用 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 */
}
Run Code Online (Sandbox Code Playgroud)

和配置:

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

创建 ContextSource 时,所有 LdapSourceProperties 的字段均为 null,但如果我取消注释,locations = "application.properties"则仅当 application.properties 位于根类路径中时它才有效。@ConfigurationProperties 使用的默认环境似乎不包含所需的属性...

替代解决方案:

最后,我将所有属性放入application-<profile>.properties文件中(并删除 @PropertySource 定义)。我现在可以使用application-test1.propertiesapplication-test2.properties。在我的测试类上,我可以设置@ActiveProfiles("test1")激活配置文件并加载关联的属性。

hzp*_*zpz 1

首先,您需要了解 Spring 的 JUnit 测试如何工作。的目的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
    }

}
Run Code Online (Sandbox Code Playgroud)

其次,Javadoc声明@ProperySource

如果给定的属性键存在于多个 .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);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用以下方式声明它@ContextConfiguration

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ExtractionBatchConfiguration.class }, 
                      initializers = MockApplicationContextInitializer.class)
public class ExtractBatchTestCase {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 最后,我将所有属性放入“application-&lt;profile&gt;.properties”中。我现在可以使用“application-test1.properties”和“application-test2.properties”。在我的测试类上,我可以设置 `@ActiveProfiles("test1")` 来激活配置文件并加载关联的属性。感谢您的帮助。 (2认同)