AndroidJUnit4ClassRunner throwing RuntimeException Android

760 views Asked by At

I am developing an Android app. I am writing the Junit test for the android and I am a novice in the Junit test case.

In-app I have one relative layout on click of that I am opening date picker dialog box and once the user selects the date I am showing in the TextView.

I want to test these actions with Junit. When I try to run the test case it is throwing me following error:

java.lang.RuntimeException: Can't create handler inside thread Thread[Instr: androidx.test.runner.AndroidJUnitRunner,5,main] that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:205)
at android.os.Handler.<init>(Handler.java:118)
at android.app.Dialog.<init>(Dialog.java:123)
at android.app.AlertDialog.<init>(AlertDialog.java:201)
at android.app.AlertDialog.<init>(AlertDialog.java:197)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:115)
at android.app.DatePickerDialog.<init>(DatePickerDialog.java:90)
at com.example.sride.DataSelectedTest.loginClickedSuccess(DataSelectedTest.java:74)

Here is my Test class:

@RunWith(AndroidJUnit4ClassRunner.class)
public class DataSelectedTest {

    private Context appContext;

    @Test
    public void useAppContext() {
        // Context of the app under test.
        appContext = ApplicationProvider.getApplicationContext();
        assertEquals("com.example.sride", appContext.getPackageName());
    }

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void datCheckSuccess() throws Throwable {
        Log.e("@Test", "Performing date check success test");
        Espresso.onView((withId(R.id.calendarRl)))
                .perform(ViewActions.click());

        // throwing error at this line
        // If I remove this line then it is working as expected
        DatePickerDialog datePickerDialog =
                new DatePickerDialog(mActivityRule.getActivity(), null, 2012, 6, 7);

        datePickerDialog.dismiss();

        Espresso.onView(withId(R.id.dateTv))
                .check(matches(withText("7" + "-" + (6 + 1) + "-" + "2012")));
    }
}

I also tried these codes to run inside runOnUiTHeard() but the problem still persists.

I also tried these codes to run inside Handler() but the test will keep on running not showing any output

Am I missing something?

1

There are 1 answers

0
Lalit Pal On

Here is a link which may solve your problem. To work on real instance of your activity, you would need either an instrumentation test or you may need to use Roboelectric.

Instrumented Unit Class Test - Can't create handler inside thread that has not called Looper.prepare()