测试类中的android.view.ViewRootImpl $ CalledFromWrongThreadException

时间:2015-11-19 18:04:06

标签: android multithreading exception testing view

我正在为一个Android应用程序的测试类工作,我正在获取android.view.ViewRootImpl $ CalledFromWrongThreadException。代码假设模拟文本字段的输入。调用语句testSearch()时,方法searchText.setText("hi");中会抛出此异常。我不知道为什么会那样做,我想解决它。这是代码:

package com.example.guy.smsclassproject;

import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.SmallTest;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;

/**
 * Created by Guy on 11/16/2015.
 */
public class DraftsActivityTest2 extends ActivityInstrumentationTestCase2<DraftsActivity>
{
    private EditText searchText;
    private Button searchButton;
    private DraftsDatabase draftsDatabase;
    ArrayList<MessageObject> messagesToBeDisplayed;
    DraftsActivity tester;
public DraftsActivityTest2()
{
    super(DraftsActivity.class);
}

@Override
public void setUp() throws Exception
{
    draftsDatabase = new DraftsDatabase();
    MessageObject messageObject1 = new MessageObject("hi", "5554", true);
    MessageObject messageObject2 = new MessageObject("hi hi", "5555554", true);
    MessageObject messageObject3 = new MessageObject("sup", "5435555554", true);
    draftsDatabase.addMessage(messageObject1);
    draftsDatabase.addMessage(messageObject2);
    draftsDatabase.addMessage(messageObject3);
    messagesToBeDisplayed = draftsDatabase.getAllTexts();
    tester = getActivity();
    messagesToBeDisplayed = tester.messagesToBeDisplayed;
    searchText = (EditText) tester.findViewById(R.id.searchText);
    searchButton = (Button) tester.findViewById(R.id.searchButton);
}

@SmallTest
public void testSearch() {
    //The problem occurs here:
    searchText.setText("hi");
    searchButton.performClick();
    messagesToBeDisplayed = draftsDatabase.getMessagesByKey(searchText.getText().toString());
    assertEquals("Messages with the word hi", 2, messagesToBeDisplayed.size());

}

}

1 个答案:

答案 0 :(得分:2)

问题是你只能从主UI线程修改小部件...... 您可以尝试将UiThreadTest注释添加到testSearch,这将使其在主线程中运行。