[FIXED] Android JUnit mock Activity context


I have a method that I want to test. It has a DatePickerDialog inside which requires a context (Activity Context). I tried to use this


But obviously, it doesn’t work

java.lang.RuntimeException: Can't create handler inside thread Thread[Instr: androidx.test.runner.AndroidJUnitRunner,5,main] that has not called Looper.prepare()

I need that DatePickerDialog only for one reason. To test that minDate and maxDate are set. Is it possible somehow to get a mock activity context?

Should I use the ActivityTestRule or ActivityScenario? Is there any other ways?

Thank you.


Solved. Just added the @UiThreadTest annotation to my test method.

Answered By – Serhii K.

Answer Checked By – Terry (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published