https://kotlinlang.org logo
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hiring-french
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
lincheck
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by
Title
r

Richard Gomez

08/20/2021, 2:17 PM
Hello! I'm trying to convert tests from JUnit -> Kotest for my Spring WebFlux + R2DBC application. Converting unit tests was easy enough using the Spring Extension, however, I'm not quite sure how to dynamically configure TestContainers for integration tests. I'm currently using this pattern to create a PostgreSQLContainer and configure Spring. How would I accomplish this using the TestContainers Extension? The main issue I'm experiencing is that
pgContainer
doesn't start until the first test is executed. However,
@DataR2dbcTest
tries to configure the Spring context before starting any tests, which obviously fails:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.r2dbc.pool.ConnectionPool]: Factory method 'connectionFactory' threw exception; nested exception is org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryOptionsInitializer$ConnectionFactoryBeanCreationException: Failed to determine a suitable R2DBC Connection URL
Caused by: org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryOptionsInitializer$ConnectionFactoryBeanCreationException: Failed to determine a suitable R2DBC Connection URL
I'm going to play around with using the PostgreSQLContainer defined in
BaseIntegrationTest
, rather than defining one in my Spec.
s

sam

08/20/2021, 2:27 PM
I think the issue is that extensions run first
so you can't get the container to run before the spring setup
I don't use spring, what does DataR2dbcTest do
r

Richard Gomez

08/20/2021, 2:37 PM
It configures everything that is required to use R2DBC: • Bootstrapping the database connection • Registering relevant beans, like
DatabaseClient
, so they can be used in Constructor injection • etc. (A bunch of 'magic', as with most Spring annotations.)
s

sam

08/20/2021, 2:37 PM
I guess my question is, what in that example is being confgured by that annotation
is the the dbClient
r

Richard Gomez

08/20/2021, 2:39 PM
With the BaseIntegrationTest example, it starts the PostgreSQL container before any other part of Spring's context, and passes the container to
Initializer : ApplicationContextInitializer<ConfigurableApplicationContext>
, which runs before anything.
I don't think there's necessarily a simple relationship between annotation and class configuration.
What's important is specify the TestProperties, like the database URL, before Spring initializes everything.
s

sam

08/20/2021, 2:41 PM
I'm trying to work this out on the example you pasted
the only member that spring knows about is the dbClient constructor parameter
in the BaseIntegrationTest you linked to, they're creating the test container manually
companion object {
        private val POSTGRES_CONTAINER = PostgreSQLContainer<Nothing>("postgres:latest")
        init {
            POSTGRES_CONTAINER.start()
        }
    }
So I guess you could do the same thing
r

Richard Gomez

08/20/2021, 2:43 PM
Would there be any benefit to using the kotest extension in that case?
Admittedly, I'm not a Spring 'expert' either, so I'm trying to work these things out as well on my end. I'm going to try testing more things, as I don't want to waste your time. I'll update this when I either hit a brick wall, or figure it out and have something to share.
s

sam

08/20/2021, 2:45 PM
If people using junit are having to create testcontainers manually then I would imagine its easier to do that as well
and just ignore the test containers extension
all the kotest extension does is call start and stop, like 2 lines of code
r

Richard Gomez

08/20/2021, 2:47 PM
Good to know. Thanks!
It seems that manually creating the container, outside of the test spec, is the way to go. Either via Spring's
@ContextConfiguration
annotation initializer:
@DataR2dbcTest
@ContextConfiguration(initializers = [BaseIntegrationTest.Initializer::class])
internal class R2dbcTest(@Autowired private val dbClient: DatabaseClient) : DescribeSpec({
Or Kotest's ProjectConfig (based on Kotest#1649 and "Using Testcontainers with Micronaut and Kotest"):
object ProjectConfig : AbstractProjectConfig() {
    override fun beforeAll() {
        TestDbContainer.start()
    }

    override fun afterAll() {
        TestDbContainer.stop()
    }
}

@DataR2dbcTest
internal class R2dbcTest(@Autowired private val dbClient: DatabaseClient) : DescribeSpec({
👍🏻 1
Using the spec's before spec/container/test/any doesn't work. A custom extension or listener could work, provided they can run before the spec class is instantiated.
s

sam

08/20/2021, 5:22 PM
I guess DataR2dbcTest requires the instance up and runnning before the class is created, which is why in the other example from Java, they're doing it in the companion object init method
If you want something to hook into the project lifecycle, you can use ProjectListener (or in 5.0 ProjectExtension as well)
r

Richard Gomez

08/20/2021, 5:47 PM
I guess DataR2dbcTest requires the instance up and runnning before the class is created,
Knowing Spring, there's likely a(n esoteric) method to defer this until after the class is created. That said, using a listener is much easier. This could likely be improved, but it starts/stops test containers only for integration tests and not unit tests.
s

sam

08/20/2021, 5:47 PM
Your listener could look for a custom annoation too if you didn't want to use supertypes
r

Richard Gomez

08/20/2021, 5:48 PM
Excellent point, I hadn't considered that. It could just hook into
@DataR2dbcTest
directly.
Thanks, Sam. I think this covers all my needs.
s

sam

08/20/2021, 5:51 PM
Ok glad we got to a good place
v

Victor Cardona

06/24/2022, 5:16 PM
@Richard Gomez I know this is an old thread, but how did you create your datasource? I'm following your example here but Spring is not picking up the JDBC URL. I have the following:
class TestDbContainer : PostgreSQLContainer<TestDbContainer>("postgres:13") {
    companion object {
        private lateinit var instance: TestDbContainer

        fun start() {
            if (!Companion::instance.isInitialized) {
                instance = TestDbContainer()
                instance.start()

                System.setProperty("DB_URL", instance.jdbcUrl)
                System.setProperty("DB_USERNAME", instance.username)
                System.setProperty("DB_PASSWORD", instance.password)
            }
        }

        fun stop() {
            instance.stop()
        }
    }
}

---
spring:
  datasource:
    url: ${DB_URL}
    username: ${DB_USERNAME}
    password: ${DB_PASSWORD}
Thanks!
r

Richard Gomez

06/29/2022, 5:50 PM
@Victor Cardona I ended up switching to use a base class where Spring managed the lifecycle of the container and not TestContainers.
@DataR2dbcTest
@Import(DatabaseConfig::class)
internal class DatabaseIT : IntegrationTest, DescribeSpec({ ...
I wish I remembered why — I think it had something to do with the properties only being set/respected when called as a part of the
ApplicationContextInitializer
hook.
v

Victor Cardona

06/30/2022, 2:17 PM
@Richard Gomez Thanks! I ended up having to do the same.