How to mock a final class with mockito

后端 未结 25 1095
日久生厌
日久生厌 2020-11-22 16:35

I have a final class, something like this:

public final class RainOnTrees{

   public void startRain(){

        // some code here
   }
}

I

25条回答
  •  囚心锁ツ
    2020-11-22 16:51

    Time saver for people who are facing the same issue (Mockito + Final Class) on Android + Kotlin. As in Kotlin classes are final by default. I found a solution in one of Google Android samples with Architecture component. Solution picked from here : https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample

    Create following annotations :

    /**
     * This annotation allows us to open some classes for mocking purposes while they are final in
     * release builds.
     */
    @Target(AnnotationTarget.ANNOTATION_CLASS)
    annotation class OpenClass
    
    /**
     * Annotate a class with [OpenForTesting] if you want it to be extendable in debug builds.
     */
    @OpenClass
    @Target(AnnotationTarget.CLASS)
    annotation class OpenForTesting
    

    Modify your gradle file. Take example from here : https://github.com/googlesamples/android-architecture-components/blob/master/GithubBrowserSample/app/build.gradle

    apply plugin: 'kotlin-allopen'
    
    allOpen {
        // allows mocking for classes w/o directly opening them for release builds
        annotation 'com.android.example.github.testing.OpenClass'
    }
    

    Now you can annotate any class to make it open for testing :

    @OpenForTesting
    class RepoRepository 
    

提交回复
热议问题