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");
    }

任何我如何修改我的代码的建议都将不胜感激

4

2 回答 2

27
@UiThreadTest
public void yourMethod() {

The @UiThreadTest annotation tells Android to build this method so that it runs on the UI thread. This allows the method to change the state of the spinner widget in the application under test. This use of @UiThreadTest shows that, if necessary, you can run an entire method on the UI thread.

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

于 2011-11-14T10:19:04.033 回答
7

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

ActivityName.this.runOnUiThread(new Runnable() {

            public void run() {
                // your code to update the UI
            }
        });
于 2011-11-14T10:22:41.870 回答