Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - AssertionFailedError on startActivity method in ActivityUnitTestCase test class

Tags:

I am trying to test an activity in a module. I am just trying to start this activity in the test method, but I always have a AssertionFailedError. I searched the web for this issue but could not find any solution. Any help is appreciated.

This is my test class:

public class ContactActivityTest extends ActivityUnitTestCase<ContactActivity> {

    public ContactActivityTest() {
        super(ContactActivity.class);
    }


    @Override
    public void setUp() throws Exception {
        super.setUp();
    }


    public void testWebViewHasNotSetBuiltInZoomControls() throws Exception {
        Intent intent = new Intent(getInstrumentation().getTargetContext(),
                ContactActivity.class);
        startActivity(intent, null, null);
    }


    @Override
    public void tearDown() throws Exception {
        super.tearDown();
    }
}

And this is the error:

junit.framework.AssertionFailedError
at android.test.ActivityUnitTestCase.startActivity(ActivityUnitTestCase.java:147)
at com.modilisim.android.contact.ContactActivityTest.testWebViewHasNotSetBuiltInZoomControls(ContactActivityTest.java:29)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1763)

Regards.

like image 640
ismail Avatar asked Jul 04 '14 14:07

ismail


1 Answers

ActivityUnitTestCase's startActivity() method needs to be called on the main thread only.

This can be done in the following ways:

  1. Use the @UiThreadTest annotation before your test method:

    @UiThreadTest
    public void testWebViewHasNotSetBuiltInZoomControls() throws Exception {
        Intent intent = new Intent(getInstrumentation().getTargetContext(),
                ContactActivity.class);
        startActivity(intent, null, null);
    }
    
  2. Use the runOnMainSync method of the Instrumentation class:

    public void testWebViewHasNotSetBuiltInZoomControls() throws Exception {
        final Intent intent = new Intent(getInstrumentation().getTargetContext(),
                ContactActivity.class);
    
        getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {
                startActivity(intent, null, null);
               }
            });
     }
    

Why am I right?

like image 90
appoll Avatar answered Oct 23 '22 06:10

appoll