2

I am, as a learning experience, trying to port the tests described in Spring Boot's kotlin tutorial (https://spring.io/guides/tutorials/spring-boot-kotlin/) from using JUnit 5 to KotlinTest.

In a repositories test annotated with @DataJpaTest, I manage to autowire my JPA repositories fine. But autowiring Spring Boot's TestEntityManager does not work, as I get java.lang.IllegalStateException: No transactional EntityManager found when I try to use it in a test.

In addition to @DataJpaTest, I tried adding @Transactional, without luck.

When running the test with JUnit5, persisting an entity with the entityManager works fine.

@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

But with KotlinTest, it fails:

@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

The error being java.lang.IllegalStateException: No transactional EntityManager found.

I haven't been able to figure out how to provide this entitymanager in the test implemented using KotlinTest.

Terje Andersen
  • 429
  • 2
  • 17
  • 1
    This seems to be a bug with KotlinTest integration with Spring. [This is the github issue](https://github.com/kotlintest/kotlintest/issues/950) for it, and [This is the PR that is working on the solution](https://github.com/kotlintest/kotlintest/pull/953). For now, what you can do is copy what is in the PR and use that listener instead until we can release the bugfix correctly. – LeoColman Aug 23 '19 at 22:22
  • This issue may provide some clue: https://jira.spring.io/browse/SPR-16550 – wangkaibule May 20 '21 at 00:28

1 Answers1

0

Just create transaction wrapper, like this:

@Component
class TransactionWrapperUtils {

    @Transactional
    public fun runWithTransaction(f: () -> Unit) {
        f()
    }
}

And call it

transactionWrapperUtils.runWithTransaction { entityManager.persist(juergen) }