CalledFromWrongThreadException exercising JUnit tests on Android
I am new to JUnit and Android and good test documentation for working with Android is hard to find.
I have a test project with classes that extend ActivityInstrumentationTestCase2. Simple tests to examine the state of the GUI (what's enabled, relative positions, etc) work as expected. However when I attempt to perform button click actions, the wrong thread exception is thrown. Anyone know how to get around this issue?
As a follow-on, does anybody have any good suggestions for free resources on test or TDD for Android? I am using Eclipse/MotoDev.
Thanks
I can get different failure traces depending on how I invoke each button, but including one here for reference:
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRoot.checkThread(ViewRoot.java:2683)
at android.view.ViewRoot.playSoundEffect(ViewRoot.java:2472)
at android.view.View.playSoundEffect(View.java:8307)
at android.view.View.performClick(View.java:2363)
at com.android.tigerslair.demo1.test.GoTest.setUp(GoTest.java:49)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
Here is the simple setup() routine:
@Override
protected void setUp() throws Exception {
super.setUp();
TigersLair activity=getActivity();
开发者_Python百科 mGoBtn = (Button) activity.findViewById(R.id.go);
mGoBtn.performClick();
}
It doesn't matter if I perform the click in setUp() or the actual test.
You need to execute all clicks in the UIThread.
This can be done by the following two examples.
@UiThreadTest
public void testApp() {
TestApp activity = getActivity();
Button mGoBtn = (Button) activity.findViewById(R.id.testbutton);
mGoBtn.performClick();
}
or
public void testApp2() throws Throwable {
TestApp activity = getActivity();
final Button mGoBtn = (Button) activity.findViewById(R.id.testbutton);
runTestOnUiThread(new Runnable() {
@Override
public void run() {
mGoBtn.performClick();
}
});
}
精彩评论