插入带有@Transactional(propagation = NOT_SUPPORTED)的Spring Batch集成测试的测试记录不会回滚

问题描述 投票:0回答:1

我想在测试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),因为这仅用于测试。

spring-batch
1个回答
0
投票

您需要将测试设置移到测试方法之外,例如,在以@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();
}
© www.soinside.com 2019 - 2024. All rights reserved.