2

我使用下面的代码来检查和取消选中 Android 的 Switch 组件。如何在 Android Junit 测试中通过触摸实用程序选中或取消选中 Switch?

        // wait 2 seconds for the start of the activity
    final FinalizeCalibrationActivity finalActivity = (FinalizeCalibrationActivity) monitorFinalActivity
            .waitForActivityWithTimeout(2000);
    assertNotNull("FinalizeCalibrationActivity is null", finalActivity);

    final Switch swtSignedRdwPortal = (Switch) finalActivity
            .findViewById(R.id.swt_signed_rdw_portal);

    JunitUtils.waitTime(3);
    swtSignedRdwPortal.setChecked(false);

    JunitUtils.waitTime(3);
    swtSignedRdwPortal.setChecked(true);
4

1 回答 1

0

我们不能直接使用 Switch 视图。它将抛出失败的断言,例如:“android-only-the-original-thread-that-c​​reated-a-view-hierarchy-can-touch-its-views”。

我用过这样重写代码,

// wait 2 seconds for the start of the activity
    final FinalizeCalibrationActivity finalActivity = (FinalizeCalibrationActivity) monitorFinalActivity
            .waitForActivityWithTimeout(2000);
    assertNotNull("FinalizeCalibrationActivity is null", finalActivity);

    final Switch swtSignedRdwPortal = (Switch) finalActivity
            .findViewById(R.id.swt_signed_rdw_portal);

    JunitUtils.waitTime(3);
    finalActivity.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            swtSignedRdwPortal.setChecked(false);
        }
    });

    JunitUtils.waitTime(3);
    finalActivity.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            swtSignedRdwPortal.setChecked(true);
        }
    });

这在 Android Junit 测试中对我来说很好用。!!!

于 2014-01-09T06:31:01.473 回答