当应用程序在Espresso中闲置时强制执行操作 - Android

时间:2017-09-25 21:03:54

标签: java android testing android-espresso

很多人问过如何让Espresso框架在执行操作或断言之前等待后台任务完成。 我了解在这些情况下, IdlingResource 通常就是答案。

我的问题恰恰相反。 我有一个Espresso正在等待的倒计时,因为ProgressBar会更新。在倒计时期间,我有一种"取消"按钮停止倒计时。

我想写的测试将设置后台任务,并检查取消按钮是否将应用程序带回上一屏幕。现在它等待后台任务完成后再尝试单击取消按钮,但取消按钮在任务完成后消失。

我将如何"强迫" Espresso执行操作(单击取消),即使应用程序没有空闲?

1 个答案:

答案 0 :(得分:0)

老实说,我认为不可能。我有同样的问题。我通过使用 UIAutomator 来单击(根据您的情况)取消按钮来修复它。

就我而言,我有一个登录按钮,然后有一张地图。在登录按钮之后甚至在MapFragment(Espresso的问题)中,该应用程序永远不会处于空闲状态,因此我不得不对登录按钮使用UIAutomator并检查登录后地图是否出现。

我将其弹出到应用程序的依赖项中:

androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'

在我的LoginTest.kt文件中:

import androidx.test.uiautomator.*
//your imports here

@RunWith(AndroidJUnit4::class)
@LargeTest
class LoginTest {
    @Rule
    @JvmField
    //your rules here
    lateinit var mDevice:UiDevice


    @Before
    fun setUp() {
        //your setUp stuff
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())

    }

    @Test
    fun checkLogin(){
        onView(withId(R.id.loginBtn)).perform(click())   //goes to LoginFragment

        mDevice.findObject(UiSelector().text("LOGIN")).click()   //clicks login button
        //this is where I had to use the UIAutomator because espresso would never be
        //idle after the login button

        mDevice.wait(Until.findObject(By.text("YOU HAVE LOGGED IN")),15000)
        //this waits until the object with the given text appears, max. wait time is 15 seconds
        //as espresso would still not be idle, I had to check if the login was successful 
        //with (again) the help of UIAutomator
    }

    @After
    fun tearDown() {

    }

}

希望这对某人有帮助