【发布时间】:2020-06-02 10:50:22
【问题描述】:
我正在尝试使用注释 @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"
}
【问题讨论】:
标签: java unit-testing kotlin testing mocking