【发布时间】:2017-10-28 10:47:48
【问题描述】:
我正在尝试使用我的 JPA 存储库将测试数据保存到 h2 中,然后供 Spring 批处理集成测试使用。
这是我的集成测试:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = Batch.class)
public class MessageDigestMailingStepIT extends AbstractBatchIntegrationTest {
@Autowired
@Qualifier("messagesDigestMailingJob")
private Job messagesDigestMailingJob;
@Autowired
private JobLauncher jobLauncher;
@Autowired
private JobRepository jobRepository;
@Autowired
private UserAccountRepository userAccountRepository;
@Autowired
private MessageRepository messageRepository;
private JobLauncherTestUtils jobLauncherTestUtils;
@Before
public void setUp() {
this.jobLauncherTestUtils = new JobLauncherTestUtils();
this.jobLauncherTestUtils.setJobLauncher(jobLauncher);
this.jobLauncherTestUtils.setJobRepository(jobRepository);
this.jobLauncherTestUtils.setJob(messagesDigestMailingJob);
}
@Test
@Transactional
public void shouldSendMessageDigestAndUpdateNotificationSent() {
UserAccount userAccount = DomainFactory.createUserAccount("me@example.com");
userAccountRepository.save(userAccount);
JobParameters jobParameters = new JobParametersBuilder().addDate("execution_date", new Date()).toJobParameters();
jobLauncherTestUtils.launchStep("messagesDigestMailingStep", jobParameters);
//Assertions
}
}
注意测试方法上的@Transactional。不幸的是,Spring 批处理使用自己的事务,而我对 @Transactional 的使用与 Spring 批处理事务发生冲突。
这是我收到的错误消息:
java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client).
有人可以建议如何插入测试数据以用于春季批量集成测试吗?
编辑:为了更好的衡量,这里是AbstractBatchIntegrationTest类的定义:
@AutoConfigureTestEntityManager
@AutoConfigureJson
@AutoConfigureJsonTesters
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles(Profiles.TEST)
@ComponentScan(basePackages = {"com.bignibou.it.configuration", "com.bignibou.configuration"})
public abstract class AbstractBatchIntegrationTest {
}
编辑:我决定只依赖@Sql注解如下:
@Sql(scripts = "insert_message.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "clean_database.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
@Test
public void shouldSendMessageDigestAndUpdateNotificationSent() {
...
【问题讨论】:
标签: spring-batch spring-transactions spring-test