KotlinでMockito2を使ってfinal classをモック化するには

Posted by on Mon, Oct 30, 2017

環境

Android Studio: 2.3.3 Kotlin: 1.1.51 Mokito: 2.11.0

build.gradleにはmockito-coreを指定

testCompile "org.mockito:mockito-core:2.11.0"

問題

kotlinで普通にクラスを作成すると、final classです。

class EventsDataSourceManager @Inject constructor(private val eventsRemoteDataSource: EventsRemoteDataSource) {

    fun eventEntities(user:String, page:Int): Single<List<EventEntity>> {
        // リモートかキャッシュを使うかの判断をココでやるとよさそう
        return eventsRemoteDataSource.eventEntities(user, page)
    }
}

その状態でmockitoを使って、モック化しようとすると、「Mockitoはfinal classはモック化できない」とエラーにになります。

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class net.kwmt27.codesearch.infrastructure.repository.datesource.EventsDataSourceManager
Mockito cannot mock/spy because :
 - final class

対策

これを可能にするには、

test/resources/mockito-extensions

フォルダを作成し、mockito-extensionsフォルダに、org.mockito.plugins.MockMakerファイルを作成します。 org.mockito.plugins.MockMakerファイルには、下記のテキストを入力しておきます。

mock-maker-inline

この状態でもう一度テストを実行します。 すると、テストが実行されます。

参考



comments powered by Disqus