SomeComponent
Spring Boot 允许将接口 ( )的所有实现列表List
注入另一个组件 ( SomeOtherComponent
),例如
@Component
interface SomeComponent
@Component
class SomeComponentImpl0 : SomeComponent
@Component
class SomeComponentImpl1 : SomeComponent
class SomeOtherComponent {
@Autowired
lateinit var impls: List<SomeComponent>
}
如何使用 MockK 注释为实现注入模拟?在
import io.mockk.MockKAnnotations
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class SomeOtherComponentTest {
@MockK
lateinit var someComponentImpl0: SomeComponentImpl0
@MockK
lateinit var someComponentImpl1: SomeComponentImpl1
@InjectMockKs
lateinit var instance: SomeOtherComponent
@BeforeEach
fun setup() {
MockKAnnotations.init(this)
}
@Test
fun testSomething() {
println(instance.impls.toString())
}
}
我得到要么
io.mockk.MockKException:
No matching constructors found:
constructor(impls : kotlin.collections.List<de.richtercloud.inject.mocks.foor.list.of.impl.SomeComponent> = <not able to lookup>)
at de.richtercloud.inject.mocks.foor.list.of.impl.SomeOtherComponentTest.setup(SomeOtherComponentTest.kt:40)
如果我使用构造函数注入和
kotlin.UninitializedPropertyAccessException: lateinit property impls has not been initialized
at de.richtercloud.inject.mocks.foor.list.of.impl.SomeOtherComponentTest.testSomething(SomeOtherComponentTest.kt:26)
如果我@Autowired var
在课堂上使用一个属性。
我通过 Maven 3.6 和 MockK 1.9.3 使用 1.3.50。