DaggerMock icon indicating copy to clipboard operation
DaggerMock copied to clipboard

org.mockito.exceptions.base.MockitoException: Mockito cannot mock this class: class MainModule.

Open noloman opened this issue 5 years ago • 3 comments

Hi,

first of all congratulations and thanks for the library, because to be honest setting up Dagger is really cumbersome.

I'm trying DaggerMock for the first time to mock my dependencies in the instrumented tests, and I'm getting the errors here.

I'm having a fairly simple test just to make sure it works:

@RunWith(AndroidJUnit4::class)
class GoalEvaluationEntryFragmentTest {
    @get:Rule
    var activityRule = ActivityTestRule(GoalEvaluationActivity::class.java)
    @get:Rule
    val rule = espressoDaggerMockRule()

    @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)
        EspressoTestUtil.disableProgressBarAnimations(activityRule)
        val fragment = GoalEvaluationEntryFragment()
        (activityRule.activity as FragmentActivity).supportFragmentManager.beginTransaction()
            .replace(R.id.mainContainer, fragment).commit()
    }

    @Test
    fun a() {

    }
}

and I'm using the espressoDaggerModule in the examples but adapted to my project:

fun espressoDaggerMockRule() =
    DaggerMock.rule<AppComponent>(
        MainModule(),
        ServicesModule(app),
        ModelsModule(app)
    ) {
        set { component -> app.component = component }
    }

val app: MDApplication get() = ApplicationProvider.getApplicationContext<Context>() as MDApplication

And the MainModule for example is:

@Module
@OpenForTesting
class MainModule {
    @Provides
    @Singleton
    fun provideUiHandler(): Handler = Handler(Looper.getMainLooper())

    @Provides
    @Singleton
    fun provideSnackBar(): SnackBar = SnackBar()
}

I tried to use both Kotlin AllOpen plugin and also DexOpener, but I'm always getting the same issue (the one in pastebin). If I remove @get:Rule val rule = espressoDaggerMockRule() from the test, it all works (but I can't mock my dependencies of course).

Is there anything else I need to do that I've maybe missed? Thanks!

noloman avatar Jun 14 '19 09:06 noloman

It seems like a configuration error somewhere, are you importing mockito-android? Is kotlin all open configured correctly?

fabioCollini avatar Jun 16 '19 15:06 fabioCollini

yes, I am doing both: mockito-android and kotlin-all-open. When it comes to the TestApplication where the TestComponent is, do I need to duplicate it and place it under the androidTest folder?

noloman avatar Jun 27 '19 09:06 noloman

Usually the TestApplication and TestComponent are only in androidTest folder. I think there is some configuration error, can you create a minimal project to reproduce it?

fabioCollini avatar Jun 28 '19 06:06 fabioCollini