Android Junit测试失败,提示"只有创建视图层次结构的原始线程才能触摸其视图。"

18

我对Android非常陌生,正在使用Robotium编写一些基础的Android测试,但是测试失败并出现以下异常:

"android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views."

以下是基本测试用例的描述:

测试用例:

public void testSearch() {
                        Activity a = getActivity();
            SearchItemActivity search = new SearchItemActivity(solo);
            search.searchText("ipod", a);   

    }

 SearchItemActivity.searchText(String) is defined as

    public void searchText(final String search, Activity act) {
                Button v = (Button) act
                .findViewById(com.test.mobile.R.id.text_search_field);
                ((Button) v).setText("");
                ((Button) v).setText(search);
                solo.sendKey(Solo.ENTER);
                solo.waitForActivity("FoundItemdDetailActivity");
                solo.assertCurrentActivity("Expected FoundItemDetail activity","FoundItemdDetailActivity");
    }

有什么建议可以修改我的代码将不胜感激


我猜这是因为你的测试用例试图解除锁屏 https://dev59.com/A2855IYBdhLWcg3wFALy#10535284 - Hieu Rocker
2个回答

27
@UiThreadTest
public void yourMethod() {

@UiThreadTest注解告诉Android构建此方法以在UI线程上运行。这允许该方法更改应用程序中测试下拉列表小部件的状态。使用@UiThreadTest表明,必要时可以在UI线程上运行整个方法。

http://developer.android.com/tools/testing/activity_test.html


7

我猜您试图从非UI线程更新UI。因此,您需要将代码放入runOnUiThread()中。

ActivityName.this.runOnUiThread(new Runnable() {

            public void run() {
                // your code to update the UI
            }
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接