I am unable to mock a Kotlin final class using Mockito 2. I am using Robolectric in addition.
This is my test code:
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class Test {
// more mocks
@Mock
MyKotlinLoader kotlinLoader;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
}
The test fails when we try to initialise the mocks in the setUp() method.
In addition, I am using the following gradle dependencies in my code:
testCompile 'org.robolectric:robolectric:3.3.2'
testCompile 'org.robolectric:shadows-multidex:3.3.2'
testCompile 'org.robolectric:shadows-support-v4:3.3.2'
testCompile("org.powermock:powermock-api-mockito2:1.7.0") {
exclude module: 'hamcrest-core'
exclude module: 'objenesis'
}
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-inline:2.8.9'
All other unit tests pass using this configuration but as soon as I try to mock the Kotlin class it throws the following error:
Mockito cannot mock/spy because :
- final class
Please note I am using Mockito version 2 and I am using the inline dependency which automatically enables the ability to mock final classes.

/mockito-extensions/org.mockito.plugins.MockMakercontaining the valuemock-maker-inline? - SeelenvirtuosetestCompile 'org.mockito:mockito-inline:2.8.9'- blackpanther/mockito-extensions/org.mockito.plugins.MockMakerwith mockito 2.8.9? Once I removed that file I started got the same error, so looks like it's still necessary to use that file even with mockito 2.8.9. - Eugene Brusov2.+instead of2.8.9). @EugeneBrusov: It's written: here (in the meantime) ... As a convenience, the Mockito team provides an artifact where this mock maker is preconfigured. Instead of using the mockito-core artifact, include the mockito-inline artifact in your project. Note that this artifact is likely to be discontinued once mocking of final classes and methods gets integrated into the default mock maker. - yasdmock-maker-inlineworks but it's really slow I recommend you to use the all-open Compiler Plugin from Kotlin - Brais Gabin