CalledFromWrongThreadException using Android JUnit tests

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 graphical interface (what is included, relative positions, etc.) are working properly. However, when I try to perform actions with a mouse click, an incorrect thread exception occurs. Does anyone know how to get around this problem?

As a follow up, does anyone have any good suggestions on free resources for testing or TDD for Android? I am using Eclipse / MotoDev.

thank

I can get different traces of failures, depending on how I call each button, but including it 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)

setup():

@Override
protected void setUp() throws Exception {
    super.setUp();
    TigersLair activity=getActivity();

    mGoBtn = (Button) activity.findViewById(R.id.go);
    mGoBtn.performClick();        
}

, setUp() .

+3
1

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

Source: https://habr.com/ru/post/1728932/


All Articles