如何通过 Robolectric 对位置提供程序进行单元测试? [英] How to unit test location provider by Robolectric?
问题描述
有很多关于单元测试位置的好文档,例如 Android - Robolectric - 单元测试请求位置更新(LocationManager) 但不幸的是没有找到任何关于位置提供者的信息.由于我是 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.
以下代码是我在活动中使用的方法.如果此方法返回 false,我将显示 cardView,否则它是不可见的.所以我实际上想测试这个视图的可见性,但在此之前我需要模拟位置提供者来返回我想要的.这是我第一步要寻找的东西.谢谢
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);
}
}
推荐答案
Robolectric 允许您调用 Settings
类并设置值:
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.
这篇关于如何通过 Robolectric 对位置提供程序进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!