Search code examples
springintegrationtestcontainersr2dbc

Setting up an integration test with r2dbc


import io.r2dbc.pool.ConnectionPool
import io.r2dbc.spi.ConnectionFactory
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
import org.springframework.beans.factory.annotation.Autowired
import java.io.IOException
import java.sql.Date
import java.util.Arrays
import java.util.function.Consumer
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.r2dbc.core.DatabaseClient
import org.springframework.test.context.junit.jupiter.SpringExtension
import reactor.test.StepVerifier
import reactor.core.publisher.Hooks

import org.junit.jupiter.api.BeforeEach
import org.springframework.boot.test.autoconfigure.data.r2dbc.DataR2dbcTest

@ExtendWith(SpringExtension::class)
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
@DataR2dbcTest
class R2dbcTemplateIT {
    @Autowired
    var orderDomain: OrderDomainRepository? = null

    @Autowired
    var database: DatabaseClient? = null
    @ClassRule
    var mysql: MySQLContainer<?> = MySQLContainer<>("mysql:5.5")
    .withDatabaseName("test")
    .withUsername("test")
    .withPassword("test")

    @BeforeEach
    fun setUp() {
        Hooks.onOperatorDebug()
        mysql.start()
        val statements: List<String> = Arrays.asList( //
            "DROP TABLE IF EXISTS customer;",
            "CREATE TABLE customer ( id SERIAL PRIMARY KEY, firstname VARCHAR(100) NOT NULL, lastname VARCHAR(100) NOT NULL);"
        )
        statements.forEach(Consumer { it: String? ->
            database!!.sql(it!!) //
                .fetch() //
                .rowsUpdated() //
                .`as`(StepVerifier::create)
                .expectNextCount(1) //
                .verifyComplete()
        })
    }

    @Test
    @Throws(IOException::class)
    fun generatesIdOnInsert() {
        val domainMetadata = customer(1L, "John", "Smith")
        orderDomain?.save(domainMetadata) //
            ?.`as`(StepVerifier::create) //
            ?.assertNext { actual ->
                assertThat(domainMetadata.id).isNull() // immutable before save
                assertThat(actual.id).isNotNull() // after save
            }?.verifyComplete()
    }
}

I am trying to run an integration test on R2DBC using R2DBCRepositories to test our a few things. I was wondering I have this except for the fact of not having any local database running hence

Error

Does anyone know have recommendation on setting up the DB within this test as well?


Solution

  • Turns out it is an issue with Kotlin not liking the way it was set up in Java.

    https://github.com/testcontainers/testcontainers-java/issues/318