Espresso測試示例

需要測試的Activity使用之前寫過的一個界面,點擊更新按鈕便下載apk並更新,代碼可見使用JobIntentService寫一個下載服務

class MainActivity : BaseMvpActivity<MainContract.View, MainContract.Presenter>(),
    MainContract.View {

    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.let {
                if (it.action == APK_DOWNLOAD_SUCCESSFUL){
                    //apk下載成功
                    showInstallationDialog(PERMISSION_REQUEST_CODE)
                }
            }
        }
    }

    override fun attachLayoutRes(): Int {
        return R.layout.activity_main
    }

    override fun createPresenter(): MainContract.Presenter {
        return MainPresenter()
    }

    override fun initData() {
        button_updateApk.setOnClickListener {
            updateApk()
        }
    }

    private fun updateApk(){
        val url = "https://raw.githubusercontent.com/xuexiangjys/XUpdate/master/apk/xupdate_demo_1.0.2.apk"
        updateApk(url,APK_DOWNLOAD_SUCCESSFUL)
        //註冊apk下載成功廣播
        registerReceiver(receiver, APK_DOWNLOAD_SUCCESSFUL)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PERMISSION_REQUEST_CODE) {
            showInstallationDialog(PERMISSION_REQUEST_CODE)
        }
    }

}

測試類也很簡單,先初始化並獲取該activity,然後調用useAppContext()測試方法獲取按鈕並點擊,下載成功後彈出更新提示,獲取該dialog並點擊更新按鈕,測試完成

class MainActivityTest {

    private lateinit var activity: MainActivity

    @get:Rule
    var mActivityRule = ActivityScenarioRule(MainActivity::class.java)

    //在Test前初始化
    @Before
    fun init() {
        mActivityRule.scenario.onActivity {
            activity = it
        }
    }

    @Test
    fun useAppContext() {
        //獲取更新按鈕
        val viewInteraction = Espresso.onView(ViewMatchers.withId(R.id.button_updateApk))
        //驗證更新按鈕是否顯示
        viewInteraction.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
        //點擊更新按鈕
        viewInteraction.perform(ViewActions.click())

        //驗證提示彈窗是否彈出
        Espresso.onView(ViewMatchers.withText(CoreMatchers.containsString("檢測到新版本是否更新")))
            .inRoot(RootMatchers.withDecorView(CoreMatchers.not(CoreMatchers.`is`(activity.window.decorView))))
            .check(ViewAssertions.matches(ViewMatchers.isDisplayed()))

        //點擊彈窗的確認按鈕
        Espresso.onView(ViewMatchers.withText("更新"))
            .inRoot(RootMatchers.withDecorView(CoreMatchers.not(CoreMatchers.`is`(activity.window.decorView))))
            .perform(ViewActions.click())
    }

}

參考:

https://developer.android.google.cn/training/testing/espresso/setup

https://blog.csdn.net/lyabc123456/article/details/89875578

https://blog.csdn.net/to_perfect/article/details/80738867

https://www.jianshu.com/p/6c1931c27057

https://blog.csdn.net/cs_lwb/article/details/102914820

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章