gpt4 book ai didi

Spring Batch - 如何使用 jobLauncherTestUtils 防止数据库提交

转载 作者:行者123 更新时间:2023-12-02 11:17:15 25 4
gpt4 key购买 nike

我有写入数据库的 Spring Batch 作业(它有一个带有 JpaItemWriter 的步骤)。我有一个集成测试,如下所示:

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("integrationTest")
public class LoadApplicationTests {

@Autowired
private Job job;

@Autowired
private JobRepository jobRepository;

@Autowired
private JobLauncher jobLauncher;

private JobLauncherTestUtils jobLauncherTestUtils;

@Before
public void setUp() throws IOException, java.text.ParseException, Exception {
jobLauncherTestUtils = new JobLauncherTestUtils();
jobLauncherTestUtils.setJob(job);
jobRepository = new MapJobRepositoryFactoryBean(new ResourcelessTransactionManager()).getObject();
jobLauncherTestUtils.setJobRepository(jobRepository);
jobLauncherTestUtils.setJobLauncher(jobLauncher);
}

@Test
public void testJob() throws Exception {
JobParametersBuilder j = new JobParametersBuilder();
JobParameters jobParameters = j.addDate("runDate", new Date())
.addString("file", testFile.getAbsolutePath())
.addString("override", "false")
.addString("weekly", "false")
.toJobParameters();

JobExecution jobExecution = jobLauncherTestUtils.launchJob(jobParameters);

Assert.assertEquals("COMPLETED", jobExecution.getExitStatus().getExitCode());
}
}

在测试中运行作业时,它会提交到数据库。如何防止提交到数据库?通常,我可以添加 @Transactional在每次测试后回滚事务。但是,当我在测试类中添加注释时,我收到:
java.lang.IllegalStateException: Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client).

更新

我已尝试添加 @Rollback到测试类。但是, JpaItemWriter仍然提交。

这是应用程序代码中事务管理器的配置:
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}

@Bean
public Step stepLoadFile(StepBuilderFactory stepBuilderFactory,
PlatformTransactionManager transactionManager,
ItemReader<MyClass> reader, ItemProcessor<MyClass,
MyClass> processor,
ItemWriter<MyClass> writer,
ReadFailureHandler readListenerSupport,
WriteFailureHandler writeListenerSupport) {
Step step = stepBuilderFactory.get("stepPersistFile")
.transactionManager(transactionManager)
.<MyClass, MyClass> chunk(1000)
.reader(reader)
.processor(processor)
.listener(writeListenerSupport)
.listener(readListenerSupport)
.writer(writer)
.build();

return step;
}

最佳答案

为了克服这个问题,我的小组简单地写了一个 @After钩子(Hook)清除已写入的数据。它不漂亮,也不理想,但它似乎让我们解决了我们的问题。

请记住,这仍会将您的作业执行写入 batch_job_execution , batch_job_execution_context , ETC。

还要认识到,您可能希望确保您的 spring.batch.job.enabled应设置为 false在您的 test/resources/application.[properties|yml] .

欢乐时光🤦‍♂️

关于Spring Batch - 如何使用 jobLauncherTestUtils 防止数据库提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39620421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com