All Downloads are FREE. Search and download functionalities are using the official Maven repository.

xyz.haff.testcontainers.customizer.MongoContainerTestContextCustomizer.kt Maven / Gradle / Ivy

There is a newer version: 0.2.2
Show newest version
package xyz.haff.testcontainers.customizer

import org.springframework.context.ConfigurableApplicationContext
import org.springframework.core.env.MapPropertySource
import org.springframework.test.context.ContextCustomizer
import org.springframework.test.context.MergedContextConfiguration
import org.testcontainers.containers.MongoDBContainer
import xyz.haff.testcontainers.annotation.MongoContainerTest

private fun createContainer(tag: String) = MongoDBContainer("mongo:$tag").apply {
    start()
}

class MongoContainerTestContextCustomizer(
    private val annotation: MongoContainerTest,
) : ContextCustomizer {

    companion object {
        private val persistentContainers: MutableMap = mutableMapOf()
    }

    override fun customizeContext(
        context: ConfigurableApplicationContext,
        mergedConfig: MergedContextConfiguration
    ) {
        val container = if (annotation.persistent) {
            persistentContainers.getOrPut(annotation.tag) {
                createContainer(annotation.tag)
            }
        } else {
            createContainer(annotation.tag)
        }


        context.environment.propertySources.addFirst(
            MapPropertySource(
                "MongoDB Testcontainer Properties",
                mapOf("spring.data.mongodb.uri" to container.replicaSetUrl)
            )
        )
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy