pixel
pixel

Reputation: 26483

Spring Boot TestContainers Create application from an existing main method in Kotlin

I have a Spring Boot application:

@SpringBootApplication
class MyApp

fun main(args: Array<String>) {
    val initConfig: SpringApplication.() -> Unit = {
        addInitializers(BeansInitializer())
    }

    runApplication<MyApp>(args = args, init = initConfig)
}

I want to run it in dev mode:

object MyAppTest {
    @JvmStatic
    fun main(args: Array<String>) {
        SpringApplication.from (MyApp << how to pass main here?)
            .with(RedisContainerDevMode::class.java)
            .run(*args)
    }
}

I don't know how to pass the main method into from.

Upvotes: 0

Views: 414

Answers (2)

pixel
pixel

Reputation: 26483

@Chazoshtare answer works, but I found a Kotlin-dedicated way to do it. There is a fromApplication extension function in Spring Boot 3.1.1.

import org.springframework.boot.fromApplication


object MyAppTest {
    @JvmStatic
    fun otherMain(args: Array<String>) {
        fromApplication<MyApp>()
                .with(RedisContainerDevMode::class.java)
                .run(*args)
    }
}

Upvotes: 3

Chazoshtare
Chazoshtare

Reputation: 36

The main function you declared in the first example file is a top level function, so if you want to refer to it in a different file, you need to use syntax like:
::functionName

Although in your case, since both functions are called main, if you try to put in in there as ::main, the compiler will assume that you're referring to the static method in the test, and not to the function that initializes your Spring application.

You have 2 options to resolve this:
- change the name of your test function to something else, then import your main function there

import your.pkg.path.main

object MyAppTest {
    @JvmStatic
    fun otherMain(args: Array<String>) {
        SpringApplication.from(::main)
                .with(RedisContainerDevMode::class.java)
                .run(*args)
    }
}

- or use an import alias to disambiguate the two methods

import your.pkg.path.main as springMain

object MyAppTest {
    @JvmStatic
    fun main(args: Array<String>) {
        SpringApplication.from(::springMain)
                .with(RedisContainerDevMode::class.java)
                .run(*args)
    }
}

Upvotes: 2

Related Questions