0

在使用 Robolectric、Espresso 和 Mockito 的单元测试中,如何验证单击按钮时函数是否运行。

val MyFragment() : Fragment {
    ...

    fun myBtnClicked() {
        ... 
    }
}

MyFragmentUnitTest,位于测试范围内。

@RunWith(RobolectricTestRunner::class)
class MyFragmentUnitTest {
    @get:Rule
    val instantExecutorRule = InstantTaskExecutorRule()

    private lateinit var scenario: FragmentScenario<MyFragment>

    @Test
    fun `myButton click`() {
        scenario = launchFragmentInContainer(
            fragmentArgs = null,
            themeResId = R.style.Theme_Words,
            initialState = Lifecycle.State.RESUMED
        )

        val myBtn = onView(ViewMatchers.withId(R.id.my_btn)
        

        myBtn
            .check(ViewAssertions.matchers(isDisplayed()))
            .check(ViewAssertions.matchers(isClickable()))
            .perform(ViewActions.click())


        // I was hoping to use a something like this
        verify(scenario).myBtnClicked()
    } 
} 

4

0 回答 0