Hesam
Hesam

Reputation: 53600

How to unit test location provider by Robolectric?

There are a lot of good docs regard unit testing location such as Android - Robolectric - Unit testing request location updates (LocationManager) but unfortunately didn't find anything regard location provider. Since I'm new to Robolectric I still have no clear insight how it works. Any idea would be appreciated.

Following code is a method I have in my activity. I display a cardView if this method returns false otherwise it is invisible. So I actually want to test visibility of this view but before this I need to mock location provider to return what I want. This is the thing that I'm looking for in first step. Thanks

private boolean isLocationEnabled()
    {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            try
            {
                locationMode = Settings.Secure.getInt(this.getContentResolver(), Settings.Secure.LOCATION_MODE);

            }
            catch (Settings.SettingNotFoundException e)
            {
                Logger.logException(e);
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        }
        else
        {
            locationProviders = Settings.Secure.getString(this.getContentResolver(),
                    Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

Upvotes: 2

Views: 2072

Answers (1)

alex.p
alex.p

Reputation: 2739

Robolectric allows you to call into the Settings class and set values:

Settings.Secure.putString(contentResolver, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, "locationProvider");

Put what you want in there and it should return what you've set in the tests.

Upvotes: 5

Related Questions