JobLauncherTestUtils在尝试测试弹出批处理步骤时抛出NoUniqueBeanDefinitionException

时间:2015-02-03 07:12:42

标签: spring spring-boot spring-batch spring-batch-admin

我正在使用Spring启动和Spring批处理。我已定义了多个工作。

我正在尝试构建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 {

}

4 个答案:

答案 0 :(得分:5)

我遇到了同样的问题,更简单的方法是注入JobLauncherTestUtils的设置者,就像Mariusz在Jira of Spring中解释的那样:

@Bean
public JobLauncherTestUtils getJobLauncherTestUtils() {

    return new JobLauncherTestUtils() {
        @Override
        @Autowired
        public void setJob(@Qualifier("ncsvImportJob") Job job) {
            super.setJob(job);
        }
    };
}

答案 1 :(得分:1)

所以我看到了jobUnderTest bean。在所有这些导入中的某个地方,您还要导入另外两个作业。我看到你的BatchConfiguration类导入了其他东西以及你打开了组件扫描。仔细追踪所有配置。有些东西正在为这些豆子定义。

答案 2 :(得分:0)

我也遇到了这个问题,无法使JobLauncherTestUtils正常工作。它可能是由this issue

引起的

我最终将SimpleJobLauncher和我的Job自动装入单元测试,并且只是

launcher.run(importAccountingDetailJob, params);

答案 3 :(得分:0)

一篇旧帖子,但我想提供我的解决方案。

在这种情况下,我会自动注册每个作业JobLauncherTestUtils

@Configuration
public class TestConfig {

    private static final Logger logger = LoggerFactory.getLogger(TestConfig.class);

    @Autowired
    private AbstractAutowireCapableBeanFactory beanFactory;

    @Autowired
    private List<Job> jobs;

    @PostConstruct
    public void registerServices() {
       jobs.forEach(j->{
         JobLauncherTestUtils u = create(j);
         final String name = j.getName()+"TestUtils"
         beanFactory.registerSingleton(name,u);
           beanFactory.autowireBean(u);
           logger.info("Registered JobLauncherTestUtils {}",name);

       });

    }

    private JobLauncherTestUtils create(final Job j) {
        return new MyJobLauncherTestUtils(j);
    }

    private static class MyJobLauncherTestUtils extends JobLauncherTestUtils {


        MyJobLauncherTestUtils(Job j) {
            this.setJob(j);
        }

        @Override // to remove @Autowire from base class
        public void setJob(Job job) {
            super.setJob(job);
        }
    }
}