Search code examples
androidmockitoandroid-testing

How to use Mockito in the AndroidTest source set


How do you use Mocks in an Integration test(AndroidTest). I'm receiving the following error.

Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)

I'm using the following dependencies.

androidTestImplementation "org.mockito:mockito-android:3.11.2" <br>
androidTestImplementation "org.mockito:mockito-core:3.11.2" <br>

I don't think dexmaker is required anymore.

androidTestImplementation "com.linkedin.dexmaker:dexmaker-mockito:2.28.1"

I've excluded the following classes because the build was complaining about multiple file paths.

    packagingOptions {
        exclude "mockito-extensions/org.mockito.plugins.MockMaker"
    }

My Fragment test looks like this

//@RunWith(MockitoJUnitRunner::class)
class DetailsFragmentTest {


//    @get:Rule
//    val mockitoRule: MockitoRule = MockitoJUnit.rule()

    private lateinit var  bundle: Bundle
    private lateinit var scenario: FragmentScenario<DetailsFragment>


    @Mock
    private lateinit var viewModel: MainViewModel

    @Before
    fun setup() {

        MockitoAnnotations.openMocks(this)

        bundle = DetailsFragmentArgs("Test").toBundle()

        scenario = launchFragmentInContainer(
            factory = MainFragmentFactory(viewModel),
            fragmentArgs = bundle,
            themeResId = R.style.Theme_Words
        )
    }

    @Test
    fun textView_WordDescription() {
        Espresso.onView(ViewMatchers.withId(R.id.tv_word))
            .check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
    }
    
}

I've tried initializing Mockito three different ways (they are ll commented out in the code above).

  1. MockitoAnnotations.openMock(this)
  2. @get:Rule val mockitoRule: MockitoRule = MockitoJunit.rule()
  3. @RunWith(MockitoJUnitRunner::class)

Solution

  • Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)

    Is caused by an incompatible version of ByteBuddy. You can check the version of ByteBuddy you are using by finding it in the External Libraries and comparing it to the version mockito-android is using, you can check the version here

    You will either need to change the mockito-android library to a version that matches the ByteBuddy version in your app or adjust the ByteBuddy to match the version in mockito-android