gpt4 book ai didi

java - lateinit 属性模拟对象尚未初始化

转载 作者:行者123 更新时间:2023-12-04 01:24:27 33 4
gpt4 key购买 nike

我正在尝试使用注释@MockBean 初始化(通过模拟)两个对象

它似乎只有在我调用方法 mock(className) 时才有效,但由于我想在多个方法上使用模拟类,我不想在我的测试方法中重复相同的代码。

这是我的测试课:

@RunWith(MockitoJUnitRunner::class)
class WordServiceTest {

@MockBean
lateinit var wordRepositoryMock: WordRepository

@MockBean
private lateinit var wordMapperMock: WordMapper

@Test
fun findAllTest() {
// Error: lateinit property wordRepositoryMock has not been initialized
val wordService = WordService(wordRepositoryMock, wordMapperMock)
`when`(wordRepositoryMock.findAll()).thenReturn(listOf(
WordEntity(UUID.randomUUID(), "xxx"),
WordEntity(UUID.randomUUID(), "xxx")))
assertEquals(2, wordService.findAll().size)
}

@Test
fun wordExistsTest() {
// This works fine
val wordRepositoryMock = mock(WordRepository::class.java)
val wordMapperMock = mock(WordMapper::class.java)
val wordService = WordService(wordRepositoryMock, wordMapperMock)
val word = "xxx"
`when`(wordRepositoryMock.existsWordEntityByName(word)).thenReturn(true)
assertEquals(true, wordService.wordExists(word))
}
}

我不想使用 Spring Boot @Autowired 注释,因为我的 spring 应用程序需要我不想加载的上下文。

我得到的错误:
lateinit property wordRepositoryMock has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property wordRepositoryMock has not been initialized

依赖项:
dependencies {
...
testImplementation("org.springframework.security:spring-security-test")
testImplementation ('org.springframework.boot:spring-boot-starter-test')
testImplementation("org.junit.jupiter:junit-jupiter:5.6.2")
testImplementation "org.junit.jupiter:junit-jupiter-params:5.5.2"
testImplementation "org.junit.jupiter:junit-jupiter-api:5.6.2"
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.6.2"
testImplementation("io.rest-assured:spring-mock-mvc:4.0.0")
testImplementation("io.mockk:mockk:1.9.3")
testImplementation "org.testcontainers:postgresql:1.11.3"
testImplementation "org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE"
runtimeOnly('org.postgresql:postgresql')
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation "org.mockito:mockito-junit-jupiter:3.3.3"
}

最佳答案

MockitoJUnitRunner@Mock 一起使用注解。
@MockBean来自 Spring,因此您需要使用 @SpringRunner .

但是,看起来您的示例不需要 Spring,因此您可以切换到 @Mock :

@RunWith(MockitoJUnitRunner::class)
class WordServiceTest {

@Mock
private lateinit var wordRepositoryMock: WordRepository

@Mock
private lateinit var wordMapperMock: WordMapper
}

如果您升级到 Junit5(我只在 Junit5 中测试过),您还可以进一步改进。构造函数参数是 lateinit 的一个很好的替代方案:

@ExtendWith(MockitoExtension::class)
class WordServiceTest(
@Mock val wordRepositoryMock: WordRepository,
@Mock val wordMapperMock: WordMapper
) {

}

关于java - lateinit 属性模拟对象尚未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62150333/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com