JobLauncherTestUtils 在尝试测试 Spring Batch 步骤时抛出 NoUniqueBeanDefinitionException

2024-01-30

我正在使用 Spring boot 和 Spring Batch。我定义了不止一项工作。

我正在尝试构建 junit 来测试作业中的特定任务。

因此我使用 JobLauncherTestUtils 库。

当我运行测试用例时,我总是得到 NoUniqueBeanDefinitionException。

这是我的测试课:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {BatchConfiguration.class})
public class ProcessFileJobTest  {

    @Configuration
    @EnableBatchProcessing
    static class TestConfig {
        @Autowired

        private JobBuilderFactory jobBuilder;
        @Autowired
        private StepBuilderFactory stepBuilder;

        @Bean
        public JobLauncherTestUtils jobLauncherTestUtils() {
            JobLauncherTestUtils jobLauncherTestUtils = new JobLauncherTestUtils();
            jobLauncherTestUtils.setJob(jobUnderTest());
            return jobLauncherTestUtils;
        }


        @Bean
        public Job jobUnderTest() {
            return jobBuilder.get("job-under-test")
                    .start(processIdFileStep())
                    .build();
        }


        @Bean
        public Step processIdFileStep() {
            return stepBuilder.get("processIdFileStep")
                    .<PushItemDTO, PushItemDTO>chunk(1) //important to be one in this case to commit after every line read
                    .reader(reader(null))

                    .processor(processor(null, null, null, null))
                    .writer(writer())

                            //     .faultTolerant()
                            //   .skipLimit(10) //default is set to 0
                            //     .skip(MySQLIntegrityConstraintViolationException.class)
                    .build();
        }


        @Bean
        @Scope(value = "step", proxyMode = ScopedProxyMode.INTERFACES)
        public ItemStreamReader<PushItemDTO> reader(@Value("#{jobExecutionContext[filePath]}") String filePath) {
            ...
            return itemReader;
        }

        @Bean
        @Scope(value = "step", proxyMode = ScopedProxyMode.INTERFACES)
        public ItemProcessor<PushItemDTO, PushItemDTO> processor(@Value("#{jobParameters[pushMessage]}") String pushMessage,
                                                                 @Value("#{jobParameters[jobId]}") String jobId,
                                                                 @Value("#{jobParameters[taskId]}") String taskId,
                                                                 @Value("#{jobParameters[refId]}") String refId)
        {
            return new PushItemProcessor(pushMessage,jobId,taskId,refId);
        }

        @Bean
        public LineMapper<PushItemDTO> lineMapper() {
            DefaultLineMapper<PushItemDTO> lineMapper = new DefaultLineMapper<PushItemDTO>();
           ...
            return lineMapper;
        }

        @Bean
        public ItemWriter writer() {
            return new someWriter();
        }
    }


    @Autowired
    protected JobLauncher jobLauncher;

    @Autowired
    JobLauncherTestUtils jobLauncherTestUtils;



    @Test
    public void processIdFileStepTest1() throws Exception {
        JobParameters jobParameters = new JobParametersBuilder().addString("filePath", "C:\\etc\\files\\2015_02_02").toJobParameters();
        JobExecution jobExecution = jobLauncherTestUtils.launchStep("processIdFileStep",jobParameters);

    }

那是例外:

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.batch.core.Job] is defined: expected single matching bean but found 3: jobUnderTest,executeToolJob,processFileJob

任何想法? 谢谢。

添加了 BatchConfiguration 类:

package com.mycompany.notification_processor_service.batch.config;

import com.mycompany.notification_processor_service.common.config.CommonConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;


@ComponentScan("com.mycompany.notification_processor_service.batch")
@PropertySource("classpath:application.properties")
@Configuration
@Import({CommonConfiguration.class})
@ImportResource({"classpath:applicationContext-pushExecuterService.xml"/*,"classpath:si/integration-context.xml"*/})
public class BatchConfiguration {

    @Value("${database.driver}")
    private String databaseDriver;
    @Value("${database.url}")
    private String databaseUrl;
    @Value("${database.username}")
    private String databaseUsername;
    @Value("${database.password}")
    private String databasePassword;



    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(databaseDriver);
        dataSource.setUrl(databaseUrl);
        dataSource.setUsername(databaseUsername);
        dataSource.setPassword(databasePassword);
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

}

这是 CommonConfiguration

@ComponentScan("com.mycompany.notification_processor_service")
@Configuration
@EnableJpaRepositories(basePackages = {"com.mycompany.notification_processor_service.common.repository.jpa"})
@EnableCouchbaseRepositories(basePackages = {"com.mycompany.notification_processor_service.common.repository.couchbase"})
@EntityScan({"com.mycompany.notification_processor_service"})
@EnableAutoConfiguration
@EnableTransactionManagement
@EnableAsync
public class CommonConfiguration {

}

我遇到了同样的问题,更简单的方法是注入设置器JobLauncherTestUtils就像 Mariusz 解释的那样春天的吉拉 https://jira.spring.io/browse/BATCH-2366:

@Bean
public JobLauncherTestUtils getJobLauncherTestUtils() {

    return new JobLauncherTestUtils() {
        @Override
        @Autowired
        public void setJob(@Qualifier("ncsvImportJob") Job job) {
            super.setJob(job);
        }
    };
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JobLauncherTestUtils 在尝试测试 Spring Batch 步骤时抛出 NoUniqueBeanDefinitionException 的相关文章

随机推荐