使用 Spring Boot、Kotest、Testcontainers 和 MongoDB 的 Bootstrap 项目


一个项目模板,其中包含开始使用 Spring Boot、Kotest、Testcontainers 和 MongoDB 所需的所有依赖项和配置。

项目模板在GitHub上可用。

项目中必不可少的是:

build.gradle.kts中的依赖项:

    implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
    implementation(
"org.springframework.boot:spring-boot-starter-web")
    implementation(
"com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation(
"org.jetbrains.kotlin:kotlin-reflect")
    testImplementation(
"org.springframework.boot:spring-boot-starter-test")
    testImplementation(
"org.testcontainers:junit-jupiter")
    testImplementation(
"org.testcontainers:mongodb")
    testImplementation(
"io.kotest:kotest-runner-junit5-jvm:5.5.5")
    testImplementation(
"io.kotest:kotest-assertions-core-jvm:5.5.5")
    testImplementation(
"io.kotest.extensions:kotest-extensions-spring:1.1.2")
    testImplementation(
"io.kotest.extensions:kotest-extensions-testcontainers:1.3.4")


IntegrationSpec是所有集成测试的基础:

@SpringBootTest
@ActiveProfiles("integration")
@AutoConfigureMockMvc
@Testcontainers
abstract class IntegrationSpec(body: ShouldSpec.() -> Unit = {}) : ShouldSpec(body) {
    override fun extensions(): List<Extension> = listOf(SpringExtension)

    @Autowired
    lateinit var mockMvc: MockMvc

    @Autowired
    lateinit var mongoOperations: MongoOperations

    override suspend fun beforeEach(testCase: TestCase) {
        super.beforeEach(testCase)
        mongoOperations.collectionNames.forEach { mongoOperations.dropCollection(it) }
    }

    companion object {
        @Container
        @JvmField
        var container = MongoDBContainer(DockerImageName.parse(
"mongo:6"))

        init {
            container.start()
        }

        @DynamicPropertySource
        @JvmStatic
        fun mongoDbProperties(registry: DynamicPropertyRegistry) {
            registry.add(
"spring.data.mongodb.uri") { container.replicaSetUrl }
        }
    }
}

通过这样的配置,您可以开始在 Docker 容器中使用 MongoDB runnig 编写测试并创建整个 Spring 上下文。