Using a mock location provider in an espresso test on Android 11+

291 views Asked by At

My Android app uses the position provided by the gps. One of my classes overrides the onProviderDisabled method of LocationListener. The app is working fine and gets the gps position.

I have an Espresso test that create a test provider for mock locations in the @Before setup() method of my test class:

locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
locationManager.addTestProvider(LOCATION_PROVIDER_NAME, false,
                                false, false, false,
                                true, true, true,
                                POWER_USAGE_HIGH, 
                                ProviderProperties.ACCURACY_FINE);
locationManager.setTestProviderEnabled(LOCATION_PROVIDER_NAME, false);

Then in my test, I call

locationManager.setTestProviderEnabled(LOCATION_PROVIDER_NAME, true);
SystemClock.sleep(200);
...
test if gps is enabled
...

On an Android 8 device, this code works fine (onProviderDisabled not called)

But on Android 11, 12 and 13 devices, about 300 ms after enabling the test provider, the onProviderDisabled is called.

What do I need to do to enable mock location on new Android devices?

1

There are 1 answers

0
Laurent D. On BEST ANSWER

I finally found the solution. It is so easy when you know it ! On recent Android devices, when using mock locations in Espresso test, you must switch ON the location service manually before running the test.

Note: this was not required on Android 8 devices