Search code examples
spring-bootkotlintestcontainersspring-boot-testcontainers

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.


Solution

  • 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)
        }
    }