Mockito 2 in Kotlin


#1

Hi,

According to several descriptions from Stackoverflow etc. I tried to use mockito 2 in my project to mock final classes/functions,

Unfortunately I could not bring it to work, because I cant figure out how to configure it correctly.
My current setup:

Mockito-dependency:
androidTestCompile 'junit:junit:4.12’
androidTestCompile ‘org.mockito:mockito-core:2.6.2’

Test-runner defined in gradle:
testInstrumentationRunner “android.support.test.runner.AndroidJUnitRunner”

Runwith-annotation on test classes:
@RunWith(AndroidJUnit4::class)

I dont want to declare my classes open only for testing, therefor I hope you could help me how to get it to work.

Thanks in advance


#2

Hello @piwo72

Did you included the “org.mockito.plugins.MockMaker” file in your project as described in the wiki section?

Cheers.


#3

After some refactoring I finally can mock and test my code.
Thank you! :smiley:


#4

Can you share more about how you got this to work? I am still getting “final” warnings despite my configuration. I can step through with the debugger and it’s clear that the classes are still marked as final even though it is walking through the AndroidByteBuddyMockMaker path. Still I get this:

org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class MyClassName
Mockito cannot mock/spy because :
 - final class

My class is in ordinary Kotlin class (and therefore, “java final.”)
Here’s my setup:

androidTestCompile "org.mockito:mockito-android:2.8.29"

(about as fresh as I can get it)
my test has

@RunWith(AndroidJUnit4::class)

Is there some other special rule or annotation or something I need to have it rewrite the classes as open/not final?