CTLocationUpdateReceiver extends BroadcastReceiver { @MainThread @Override public void onReceive(final Context context, final Intent intent) { final PendingResult result = goAsync(); try { CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Location updates receiver called"); final LocationResult locationResult = LocationResult.extractResult(intent); if (locationResult != null && locationResult.getLastLocation() != null) { Thread thread = new Thread() { public void run() { PushLocationEventTask pushLocationEventTask = new PushLocationEventTask(context, locationResult); Future<?> future = CTGeofenceTaskManager.getInstance() .postAsyncSafely("PushLocationEvent", pushLocationEventTask); try { if (future != null) { future.get(BROADCAST_INTENT_TIME_MS, TimeUnit.MILLISECONDS); } } catch (TimeoutException e) { CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Timeout location receiver execution limit of 10 secs"); } catch (Exception e) { CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Exception while processing location receiver intent"); e.printStackTrace(); } finishPendingIntent(result); } }; thread.start(); } else { CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Location Result is null"); finishPendingIntent(result); } } catch (Exception e) { finishPendingIntent(result); CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Exception while processing location updates receiver intent"); e.printStackTrace(); } CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Returning from Location Updates Receiver"); }  @MainThread @Override void onReceive(final Context context, final Intent intent);  }
@Test public void testOnReceiveWhenLastLocationNotNull() { CTLocationUpdateReceiver receiver = new CTLocationUpdateReceiver(); CTLocationUpdateReceiver spy = Mockito.spy(receiver); when(spy.goAsync()).thenReturn(pendingResult); final Boolean[] isFinished = {false}; doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { isFinished[0] = true; return null; } }).when(pendingResult).finish(); Intent intent = new Intent(); intent.putExtra("com.google.android.gms.location.EXTRA_LOCATION_RESULT", locationResult); spy.onReceive(application, intent); await().until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return isFinished[0]; } }); verify(pendingResult).finish(); }
@Test public void testOnReceiveWhenLocationResultIsNull() { CTLocationUpdateReceiver receiver = new CTLocationUpdateReceiver(); CTLocationUpdateReceiver spy = Mockito.spy(receiver); when(spy.goAsync()).thenReturn(pendingResult); spy.onReceive(application, null); verify(pendingResult).finish(); }