By default Kotlin classes final and you can’t use mock on finals. Now, today this is a not a problem with Mockito 2.10+ with inline mocking feature flag. But, on Android is not as simple, you can use inline mocking, but, with Dexmaker-inline and targeting Android 8+.

But, what if we could make kotlin classes open in our test build but also keep them final in our releases builds? Then we can mock in our tests without having to make classes always open.

Having open debug and close release class can be done with the Kotlin compiler plugin kotlin-allopen. Now, don’t freak out just yet, the plugin does not implicitly make everything open by default. We need to tell allopen what classes we want to be opened for testing, and we do this by annotating classes we want to be opened.

Let’s create our annotation to mark classes for allopen to open. We will start with the debug variant, so, be sure you put this in your src/debug directory; otherwise, it will be open in release builds if you just use src/main.

Next, we need to provide a NOP double for the OpenForTesting. So, create an implementation in release and leave out the OpenClass, make sure you put this class in the src/release.

Finally, we need to configure the kotlin-allopen and apply the plugin and this is why we omit the OpenClass in a release variant. Since the plugin is looking for the OpenClass or any annotation annotated with OpenClass it won’t find any class to make open in our release build.

Add the classpath to the root build.gradle file.

Then in the app build.gradle apply the plugin and specify the annotation class.

Now, all we need to do is annotate the classes we want to mock with OpenForTesting and we can mock in all API versions for androidTest’s.

I would like to thank @yigitboyar for his work on Android Architecture Components GithubBrowserSample which is where I first found this method for mocking in AndroidTests. I hope this article helps people searching for how mock in AndroidTest. And finally, check out the Android Architecture Components GithubBrowserSample for more detailed examples of how allopen is put in practices for testing and other awesome tricks.