エラーの状況
次のようにテストケースを写経していました。
@RunWith(MockitoJUnitRunner::class)
class MockAnnotationWheneverTest {
@Mock
private lateinit var accountRepository : AccountRepository
@InjectMocks
private lateinit var accountService : AccountServiceImpl
@Test
fun fuga() {
whenever(accountRepository.findById(1))
.thenReturn(Account("Alice"))
assertEquals(
"Alice",
accountService.findById(1).name)
}
}
Code language: Kotlin (kotlin)
テストを実行したところ、テスト失敗です。
lateinit property accountRepository has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property accountRepository has not been initialized
Code language: plaintext (plaintext)
@Mockをつけた accountRepository のインスタンスが生成されていないよ、とのことです。
mockit-kotlinのバージョンは、2.2.0 です。
// build.gradle.kts
testImplementation("junit:junit:4.12")
testImplementation("io.kotlintest:kotlintest-runner-junit4:3.4.2")
testImplementation("com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0")
Code language: plaintext (plaintext)
解決方法
stackoverflow先生によると、@BeforeEachで、次のように書くといいそうです。
@BeforeEach
fun setUp() {
MockitoAnnotations.openMocks(this)
}
Code language: Kotlin (kotlin)
全体を示すと、
@RunWith(MockitoJUnitRunner::class)
class MockAnnotationWheneverTest {
@Mock
private lateinit var accountRepository : AccountRepository
@InjectMocks
private lateinit var accountService : AccountServiceImpl
@BeforeEach
fun setUp() {
MockitoAnnotations.openMocks(this)
}
@Test
fun fuga() {
whenever(accountRepository.findById(1))
.thenReturn(Account("Alice2"))
assertEquals(
"Alice2",
accountService.findById(1).name)
}
}
Code language: Kotlin (kotlin)

stackoverflowやqiitaのお世話になりっぱなしだね!

lateinit property mock object has not been initialized
I'm trying to initialize (by mocking) two objects with the annotation @MockBean It seems only to work if i call the meth...