我想在测试Spring Batch作业时插入测试记录。
通常,我会用@Transactional
注释测试类,但这不适用于使用@SpringBatchTest注释的测试类。
@SpringBatchTest
@SpringBootTest
@Transactional
public class JobTest {
@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
void someTest() throws Exception {
jdbcTemplate.update("insert into some_table (some_col1, some_col2) values ('foo', 'bar')");
jobLauncherTestUtils.launchJob();
}
}
Existing transaction detected in JobRepository. Please fix this and try again (e.g. remove @Transactional annotations from client).
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:177)
我也尝试过@Transactional(propagation = NOT_SUPPORTED)
,但记录不会回滚。这是https://stackoverflow.com/a/46546171/10243546
我只想要测试记录,所以我不确定此答案是否适用(https://stackoverflow.com/a/55001568/10243546),因为这仅用于测试。
您需要将测试设置移到测试方法之外,例如,在以@Before
(JUnit 4)或@BeforeEach
(JUnit 5)注释的方法中。类似于:
@Before
public void initData() {
jdbcTemplate.update("insert into some_table (some_col1, some_col2) values ('foo', 'bar')");
}
@Test
void someTest() throws Exception {
jobLauncherTestUtils.launchJob();
}