尝试模拟NavController时出错

时间:2019-06-17 16:06:36

标签: android mockito androidx

尝试遵循示例https://developer.android.com/guide/navigation/navigation-testing,我遇到了预期的错误

org.mockito.exceptions.base.MockitoException: Mockito无法模拟此类:androidx.navigation.NavController类。

甚至在此处包括所有依赖项后,如下所示:https://developer.android.com/training/testing/set-up-project

@RunWith(AndroidJUnit4::class)
class MyShopFragmentTest {

    @Test
    fun testMyShopScenario_F001() {
        // Create a mock NavController
        val mockNavController = mock(NavController::class.java)

        // Create a graphical FragmentScenario for the MyShopFragment
        val myShopFragmentScenario = launchFragmentInContainer<MyShopFragment>()

        // Set the NavController property on the fragment
        myShopFragmentScenario.onFragment { fragment ->
            Navigation.setViewNavController(fragment.requireView(), mockNavController)
        }

        // Verify that performing a click prompts the correct Navigation action
        onView(ViewMatchers.withId(R.id.search)).perform(ViewActions.click())
        verify(mockNavController).navigate(R.id.searchFragment)
    }
}

有什么主意吗?

2 个答案:

答案 0 :(得分:1)

对我来说,将依赖关系从

androidTestImplementation 'org.mockito:mockito-core:3.2.4'

androidTestImplementation 'org.mockito:mockito-android:3.2.4'

运作良好。

答案 1 :(得分:0)