spring - 如何在@InjectMockKs 测试实例中注入(inject)实现列表?

标签 spring spring-boot kotlin dependency-injection mockk

Spring Boot 允许将接口(interface) ( SomeComponent ) 的所有实现列表注入(inject)为 List进入另一个组件( SomeOtherComponent ),例如

@Component
interface SomeComponent
@Component
class SomeComponentImpl0 : SomeComponent
@Component
class SomeComponentImpl1 : SomeComponent
class SomeOtherComponent {
    @Autowired
    lateinit var impls: List<SomeComponent>
}

如何使用 MockK 注释为实现注入(inject)模拟?在
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)

如果我使用构造函数注入(inject)和
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类中的属性(property)。

我通过 Maven 3.6 和 MockK 1.9.3 使用 1.3.50。

最佳答案

添加 @ExtendWith(MockKExtension::class)在您的测试类之上制作 @InjectMokKs工作。

关于spring - 如何在@InjectMockKs 测试实例中注入(inject)实现列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57709100/

相关文章:

kotlin - Receivea()在Corda中有什么用途?如何执行呢?

android - 警报对话框不适应暗模式和非暗模式

java - Spring 从 REQUIRED_NEW 方法调用 REQUIRED 方法

java - JPA 序列化/反序列化嵌套自动生成字段

amazon-web-services - 如何将 AWS Elasticache Redis 集群连接到 Spring Boot 应用程序?

spring - Drools 无法在 Spring Boot 项目中加载规则

kotlin - 何时为类中的协程指定 Dispatchers.xxx

java - @CacheEvict 的 Gemfire EntryNotFoundException

java - HTTP 状态 404 – 未找到 -hibernate-spring mvc--

java - Spring 服务器 Bean 创建问题