How to use Kotlin beans dsl initializer in SpringBootTest

回眸只為那壹抹淺笑 提交于 2019-12-11 05:44:44

问题


I have a simple application with several beans declared with kotlin beans dsl:

@SpringBootApplication
class App

val beans = beans {
    bean<A>()
}

fun main(args: Array<String>) {
    runApplication<MatchmakerApp>(*args) {
        addInitializers(beans)
    }
}

@RestController
class AppController(val a: A) {
    // some code
}

class A

and I have an integration test:

@RunWith(SpringRunner::class)
@SpringBootTest
class AppControllerTest {
    @Test
    fun dummyTest() {
        assert(true)
    }
}

Launching this test I'm getting

UnsatisfiedDependencyException: Error creating bean with name appController 
Caused by: NoSuchBeanDefinitionException: No qualifying bean of type 'A' available:`

It seems beans initializer was not invoked during SpringBootTest context creation.

What do we need to add kotlin bean dsl initializer in SpringBootTest?

The general way with @ContextConfiguration(initializers = ...) does not work here, because it looks for classes.


回答1:


Option 1

add FuBeansInitializer in the same package with App class in test directory

class FuBeansInitializer : ApplicationContextInitializer<GenericApplicationContext> {
    override fun initialize(context: GenericApplicationContext) = beans.initialize(context)
}

add context.initializer.classes into test application.properties

context.initializer.classes=path.to.FuBeansInitializer

As a result there will be nothing modified in source files. And tests will work fine.




回答2:


You can even have multiple ApplicationContextInitializer and provide a comma separated list of them in your properties(order matters). This can be useful if you used Initializer in your main code and would want to override some of your beans using, again, bean definition dsl.



来源:https://stackoverflow.com/questions/51391485/how-to-use-kotlin-beans-dsl-initializer-in-springboottest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!