2017-03-08 221 views
4

我目前正在使用spring批處理的spring引導項目。我正嘗試使用JavaConfig而不是xml,但對於當前所有的xml文檔都很困難。Spring批處理Java配置JobLauncherTestUtils

我跟着https://blog.codecentric.de/en/2013/06/spring-batch-2-2-javaconfig-part-5-modular-configurations,但在使用JobLauncherTestUtils時遇到困難。我知道我需要告訴測試使用正確的春天背景,但我似乎無法弄清楚如何去做。我得到以下錯誤:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.batch.test.JobLauncherTestUtils' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 

我的測試如下所示:

@RunWith(SpringRunner.class) 
@SpringBootTest(classes = {MyApplication.class, MyJobConfiguration.class}) 
public class RetrieveDividendsTest { 

    @Autowired 
    private JobLauncherTestUtils jobLauncherTestUtils; 

    @Test 
    public void testSomething() throws Exception { 
     jobLauncherTestUtils.launchJob(); 
    } 

} 
+0

您是否曾嘗試將TestExecutionListener註釋添加到測試類以注入配置的應用程序上下文? '@TestExecutionListeners({的DependencyInjectionTestExecutionListener.class, })' 看一看http://docs.spring.io/spring-batch/reference/html/testing.html#testingIndividualSteps怎麼看工作,如何在那裏測試單個步驟。 –

+0

@Sander_M但要做到這一點,我需要有'JobLauncherTestUtils'工作這是我的問題。我正在嘗試進行端到端或個別步驟測試,而不僅僅是測試組件。 –

回答

0

你有沒有在你的pom.xml以下?

<dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-batch</artifactId> 
</dependency> 

如果我沒有記錯的話,和你用春天開機,它應該加載彈簧批給你的自動配置豆所以他們將可用於注射。

+0

是的,我有依賴。代碼編譯只是無法獲得正確的上下文。 –

+0

Spring引導使用以下模式在測試環境中查找您的配置:1)在您的測試包中搜索最近的'@ SpringBootApplication'。 2)在主包中搜索最近的'@ SpringBootApplication'。你有這些嗎?如果不是,你可以用'@ ComponentScan'在你的測試平臺中創建一個搜索'@ Configuration'文件的文件。 – Tom

5

我偶然發現了同一個問題,並且看到了Spring Batch示例中的this XML configuration。根據我設法得到它的工作:

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(classes = { BatchTest.BatchTestConfig.class }) 
public class BatchTest { 

    @Autowired 
    private JobLauncherTestUtils jobLauncherTestUtils; 

    @Test 
    public void demo() throws Exception { 
     JobExecution jobExecution = jobLauncherTestUtils.launchJob(); 

     Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); 
    } 

    @Configuration 
    @EnableBatchProcessing 
    static class BatchTestConfig { 

     @Bean 
     JobLauncherTestUtils jobLauncherTestUtils() { 
      return new JobLauncherTestUtils(); 
     } 

     // rest omitted for brevity 
    } 
} 

測試成功和我ItemWriter記錄該處理的元素如預期。

+0

由於某種原因使用這種方法,我得到了「沒有可用的org.springframework.batch.core.Job類型的bean」,直到我將BatchTestConfig移動到其自己的類中。春天的怪癖我從來沒有遇到過或者我不知道的錯誤......否則+1 – dgtc