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

sur*_*rya 16 android robotium

我是Android的新手,我正在使用Robotium编写一些基本的Android测试,但这个例外失败了

"android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views."
Run Code Online (Sandbox Code Playgroud)

以下是基本的测试用例解释: -

测试用例:-

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");
    }
Run Code Online (Sandbox Code Playgroud)

任何有关如何修改我的代码的建议都将受到赞赏

Luk*_*cek 26

@UiThreadTest
public void yourMethod() {
Run Code Online (Sandbox Code Playgroud)

@UiThreadTest注释告诉Android构建此方法,以便它在UI线程上运行.这允许该方法更改正在测试的应用程序中的微调框小部件的状态.@UiThreadTest的这种使用表明,如果需要,您可以在UI线程上运行整个方法.

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


Lal*_*ani 6

我想你正在尝试从非UI线程更新UI.所以为此你需要把你的代码放在里面runOnUiThread().

ActivityName.this.runOnUiThread(new Runnable() {

            public void run() {
                // your code to update the UI
            }
        });
Run Code Online (Sandbox Code Playgroud)