【问题标题】:How to save test data to be consumed by a spring batch integration test如何保存测试数据以供 Spring 批处理集成测试使用
【发布时间】: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


    【解决方案1】:

    从测试中删除@Transactional,以便UserAccount 立即持久化到数据库中。然后使用@SqlExecutionPhase.AFTER_TEST_METHOD 执行清理脚本(或内联 语句)手动撤消测试期间执行的更改。

    【讨论】:

    • 嗨,山姆!谢谢。我决定只依赖@Sql 注释,因为当我使用存储库并且没有@Transactional 时,我什至没有在日志中看到hibernate/sql 插入语句...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 2018-05-22
    • 2021-05-11
    • 2013-04-19
    • 2018-11-24
    相关资源
    最近更新 更多