如何在AndroidTest源码集中使用Mockito

How to use Mockito in the AndroidTest source set

如何在集成测试 (AndroidTest) 中使用 Mocks。我收到以下错误。

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

我正在使用以下依赖项。

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

我认为不再需要 dexmaker。

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

我排除了以下 classes 因为构建抱怨多个文件路径。

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

我的 Fragment 测试是这样的

//@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()))
    }
    
}

我尝试了三种不同的方式来初始化 Mockito(它们会在上面的代码中被注释掉)。

  1. MockitoAnnotations.openMock(这个)
  2. @get:规则 val mockitoRule: MockitoRule = MockitoJunit.rule()
  3. @RunWith(MockitoJUnitRunner::class)

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

ByteBuddy版本不兼容造成的。您可以通过在外部库中找到它并与 mockito-android 正在使用的版本进行比较来检查您正在使用的 ByteBuddy 的版本,您可以检查版本 here

您需要将 mockito-android 库更改为与您应用中的 ByteBuddy 版本匹配的版本,或者调整 ByteBuddy 以匹配 [=13= 中的版本]