How to unit test location provider by Robolectric?

我们两清 提交于 2019-12-13 00:25:27

问题


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);
        }
    }

回答1:


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.



来源:https://stackoverflow.com/questions/31260337/how-to-unit-test-location-provider-by-robolectric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!