作为学习经验,我正在尝试将Spring Boot的kotlin教程(https://spring.io/guides/tutorials/spring-boot-kotlin/)中描述的测试从使用JUnit 5移植到KotlinTest。
在一个用@DataJpaTest注释的存储库测试中,我设法很好地自动部署了我的JPA存储库。但是,自动装配Spring Boot的TestEntityManager不起作用,因为当我尝试在测试中使用它时,会得到java.lang.IllegalStateException: No transactional EntityManager found。
除了@DataJpaTest之外,我还尝试添加了@Transactional,但没有成功。
在使用JUnit5运行测试时,使用entityManager持久化实体可以很好地工作。
@DataJpaTest
class RepositoriesTests @Autowired constructor(
val entityManager: TestEntityManager,
val userRepository: UserRepository,
val articleRepository: ArticleRepository) {
@Test
fun `When findByIdOrNull then return article`() {
val juergen = User(login = "springjuergen", firstname = "Juergen", lastname = "Hoeller")
entityManager.persist(juergen) <--- OK但对于KotlinTest,它失败了:
@DataJpaTest
class RepositoriesTests @Autowired constructor(
val entityManager: TestEntityManager,
val userRepository: UserRepository,
val articleRepository: ArticleRepository) : StringSpec() {
init {
"When findByIdOrNull then return article" {
val juergen = User(login = "springjuergen", firstname = "Juergen", lastname = "Hoeller")
entityManager.persist(juergen) <--- FAIL错误是java.lang.IllegalStateException: No transactional EntityManager found。
我还没有弄清楚如何在使用KotlinTest实现的测试中提供这种entitymanager。
发布于 2021-06-30 16:58:06
只需创建事务包装器,如下所示:
@Component
class TransactionWrapperUtils {
@Transactional
public fun runWithTransaction(f: () -> Unit) {
f()
}
}并将其称为
transactionWrapperUtils.runWithTransaction { entityManager.persist(juergen) }https://stackoverflow.com/questions/57607764
复制相似问题