我正在尝试对一个位置跟踪服务进行单元测试。我试图使用locationManager.addTestProvider和setTestProviderLocation方法来实现这一点。然而,似乎无法让任何位置通过提供程序并触发我的LocationListener。以下是我的代码:
public void testGettingLocations() {
mLocationManager = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
if (mLocationManager.getProvider(TEST_PROVIDER) != null) {
mLocationManager.removeTestProvider(TEST_PROVIDER);
}
mLocationManager.addTestProvider(TEST_PROVIDER, false, false, false, false, false, false, false, Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
mLocationManager.setTestProviderEnabled(TEST_PROVIDER, true);
mLocationManager.setTestProviderStatus(TEST_PROVIDER, LocationProvider.AVAILABLE, null, System.currentTimeMillis());
locations = new ArrayList<Location>();
mLocationManager.requestLocationUpdates(TEST_PROVIDER, 0, 0, ll);
for (int i = 0; i<130; i++) {
Location loc = new Location(TEST_PROVIDER);
loc.setLatitude(0 + i);
loc.setLongitude(130 - i);
loc.setTime(System.currentTimeMillis());
loc.setSpeed(0);
loc.setAccuracy(25);
loc.setAltitude(0);
loc.setBearing(0);
mLocationManager.setTestProviderLocation(TEST_PROVIDER, loc);
}
assertEquals(130, locations.size());
}
LocationListener ll = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onLocationChanged(Location location) {
locations.add(location);
Log.d("TEST", "lat: " + location.getLatitude() + ", lon: " + location.getLongitude());
}
};
断言失败是因为locations.size()返回的是0,而我的locationlistener中的日志语句没有被打印出来。有人尝试使用这些方法来单元测试位置服务吗?