2014-01-11 38 views
4

有沒有人可以幫我找出解決以下異常的方法,我想我不太瞭解事務傳播機制,這會妨礙我理解異常的真正意義留言如下,所以請幫助我理解整件事情,非常感謝你!在單元測試中使用Spring批處理JobRepository的事務問題

java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client). 
at org.springframework.batch.core.repository.support.AbstractJobRepositoryFactoryBean$1.invoke(AbstractJobRepositoryFactoryBean.java:164) 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) 
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) 
at com.sun.proxy.$Proxy15.createJobExecution(Unknown Source) 
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:111) 
at TestJob.testExcelParserTasklet(TestJob.java:36) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
at java.lang.reflect.Method.invoke(Method.java:597) 
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80) 
at org.testng.internal.MethodInvocationHelper$1.runTestMethod(MethodInvocationHelper.java:169) 
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.run(AbstractTestNGSpringContextTests.java:158) 

這是導致上述異常的代碼:

public class TestJob extends BaseTest { 
@Test 
public void testExcelParserTasklet() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, NoSuchJobException { 
    Job job = jobRegistry.getJob("parseExcelJob"); 
    jobLauncher.run(job, new JobParameters()); 
    } 
} 

這裏是BaseTest:

@ContextConfiguration("classpath:application-context.xml") 
public abstract class BaseTest extends AbstractTransactionalTestNGSpringContextTests 
{ 
    @Autowired 
    protected JobRegistry jobRegistry; 

    @Autowired 
    protected JobLauncher jobLauncher; 
} 

回答

7

AbstractTransactionalTestNGSpringContextTests包裝在一個事務中的所有測試方法。 Spring批處理作業存儲庫不喜歡與其他人共享其事務管理器。 邏輯很簡單,如果您在步驟失敗時與步驟事務管理器共享作業事務管理器,它將回滾寫入作業存儲庫的步驟和數據。這意味着您不會爲重新啓動作業而保留數據。因此,使用事務單元測試是棘手的。

查看Spring Batch文檔的4.3.1. Transaction Configuration for the JobRepository部分。

我們也遇到過這個問題,所以我們要避免交易測試,直到找到解決方案。 多事務管理器的使用可能會起作用,但我還沒有嘗試過,但看到How to configure mutliple transaction managers with Spring + DBUnit + JUnit

+0

感謝您提供如此富有洞察力的評論,您聲明的原因/邏輯是我一直在尋找的。 – user3184625

+7

如果您希望編寫在測試結束時回滾的集成測試,那麼有什麼建議? – Snekse

相關問題