如何保存测试数据以通过春季批处理集成测试消耗



我正在尝试使用我的JPA存储库来按顺序将测试数据保存到H2中,然后通过Spring Batch Integration Test Test 进行使用。

这是我的集成测试:

@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。不幸的是,春季批处理使用了自己的交易,我对@Transactional冲突与春季批处理交易的使用。

这是我收到的错误消息:

java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client).

有人可以建议如何插入测试数据以进行春季批次集成测试吗?

edit :为了很好地度量,这是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() {
...

从测试中删除@Transactional,以便立即将UserAccount持续到数据库中。然后,将@SqlExecutionPhase.AFTER_TEST_METHOD一起执行清理脚本(或 iNlined 语句(,以手动删除测试过程中执行的更改。

最新更新