私はmockitoに慣れていないので、この動作が正常かどうかはわかりません。
これは単純なサンプルクラスです。
open class Example( val example2: Example2) {
fun getStuff(fileName: String) : String {
return example2.getFileExtension(fileName)
}
}
open class Example2(val fileUtils: FileUtils) {
fun getFileExtension(fileName: String): String {
return fileUtils.getExtension(fileName)
}
}
したがって、このコードでテストしようとすると、次のようになります。
class ExampleTest {
lateinit var example: Example
val example2 = mock(Example2::class.java)
@Before
fun init() {
example = Example(example2)
}
@Test
fun getFileExtensionTest() {
val resultExpected = "jpg"
`when`(example2.getFileExtension(ArgumentMatchers.anyString())).thenReturn("jpg")
assertThat(example.getStuff("hello.jpg"), `is`(resultExpected))
}
}
実行return fileUtils.getExtension(fileName)
時にNullPointerExceptionが発生します'when'
それで'when'
、あざけると思われる機能を実行しています。
わかった!!
Kotlinはデフォルトで関数をfinalにし、mockitoはfinal関数/クラスをモックできません。したがって、ここには2つの解決策があります。
open
関数に追加
または、mockitoにfinalクラスと関数を使用させる:Mockito2がfinalをサポートするようになりました
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加