2015-11-19 74 views
0

我正在爲一個android應用程序的測試類,我得到一個android.view.ViewRootImpl $ CalledFromWrongThreadException。該代碼假設模擬輸入到文本字段中。當調用語句searchText.setText("hi");時,此方法在testSearch()中引發。我不知道它爲什麼這樣做,我想解決它。下面是代碼:

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()); 

} 

}

回答

2

的問題是,你只能修改小部件從主UI線程... 你可以嘗試添加UiThreadTest註釋testSearch這將導致它運行在主線程中。

+0

非常感謝!它現在有效。 – Oshyrath

相關問題