我是 JUnit 和 Android 的新手,很难找到使用 Android 的良好测试文档。
我有一个测试项目,其中包含扩展 ActivityInstrumentationTestCase2 的类。检查 GUI 状态(启用的内容、相对位置等)的简单测试按预期工作。但是,当我尝试执行按钮单击操作时,会抛出错误的线程异常。任何人都知道如何解决这个问题?
作为后续,有人对 Android 测试或 TDD 的免费资源有什么好的建议吗?我正在使用 Eclipse/MotoDev。
谢谢
根据我如何调用每个按钮,我可以获得不同的失败痕迹,但在这里包括一个以供引用:
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)
这是简单的 setup() 例程:
@Override
protected void setUp() throws Exception {
super.setUp();
TigersLair activity=getActivity();
mGoBtn = (Button) activity.findViewById(R.id.go);
mGoBtn.performClick();
}
无论我是在 setUp() 中执行点击还是实际测试都没有关系。
最佳答案
您需要在 UIThread 中执行所有点击。
这可以通过以下两个例子来完成。
@UiThreadTest
public void testApp() {
TestApp activity = getActivity();
Button mGoBtn = (Button) activity.findViewById(R.id.testbutton);
mGoBtn.performClick();
}
或
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();
}
});
}
关于java - CalledFromWrongThreadException 在 Android 上执行 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2087164/