android – Espresso如何测试Activity是否完成?

前端之家收集整理的这篇文章主要介绍了android – Espresso如何测试Activity是否完成?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想声明当我执行某些操作时,我正在测试的Acitivty已经完成.不幸的是,到目前为止,我只是通过在测试结束时添加一些睡眠来断言.有没有更好的办法 ?
import android.content.Context;
import android.os.Build;
import android.support.test.rule.ActivityTestRule;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import static org.junit.Assert.assertTrue;

@SuppressWarnings("unchecked")
@RunWith(JUnit4.class)
@LargeTest
public class MyActivityTest {

    Context context;

    @Rule
    public ActivityTestRule<MyActivity> activityRule
            = new ActivityTestRule(MyActivity.class,true,false);

    @Before
    public void setup() {
        super.setup();
        // ...
    }

    @Test
    public void finishAfterSomethingIsPerformed() throws Exception {

        activityRule.launchActivity(MyActivity.createIntent(context));

        doSomeTesting();

        activityRule.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                fireEventThatResultsInTheActivityToFinishItself();
            }
        });

        Thread.sleep(2000); // this is needed :(

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            assertTrue(activityRule.getActivity().isDestroyed());
        }

    }

}

解决方法

在我的情况下,我可以测试isFinishing():

assertTrue(activityTestRule.getActivity()isFinishing());

代替:

Thread.sleep(2000); // this is needed :(

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        assertTrue(activityRule.getActivity().isDestroyed());
    }

isFinishing()的另一个优点是,您不需要版本检查.

原文链接:https://www.f2er.com/android/310847.html

猜你在找的Android相关文章