How to unit test location services pop up in Android

293 Views Asked by At

I'm really trying to wrap my head around unit testing. Could use a little help for a road block. I'm trying to click the location popup buttons when asking for location permissions. I'm using JUnit 4 and expresso. Here's my test rule:

@get:Rule
val testRule: ActivityTestRule<MyActivity> = ActivityTestRule(MyActivity::class.java)

I got a set up function:

@Before
fun setUp() {
    mActivity = testRule.activity
    mFragment = MyFragment.newInstance()
}

And finally my button click test:

@Test
fun testLocationClick(){
    Assert.assertNotNull(onView(withId(R.id.button_turn_on_location)))
    onView(withId(R.id.button_turn_on_location)).perform(click())

    onView(withText("Allow all")).perform(click())

This last line saying "Allow all" was my attempt to try and click on the allow button but it does not work. Here's an attached image showing what I'm trying to click. Image

1

There are 1 best solutions below

1
On

Shameless self-plug: I wrote an article describing a solution to a similar problem back in 2016 called Testing Runtime Permissions: Lessons Learned, hope it's still useful. TLDR: since the permission dialog is a system dialog and lives outside of your app's process, it's not reachable with Espresso. You'd need to use the UI Automator, which offers more possibilities in terms of accessing system UI from under test.