CTGeofenceReceiver extends BroadcastReceiver { @MainThread @Override public void onReceive(final Context context, final Intent intent) { if (intent == null) { return; } final PendingResult result = goAsync(); try { CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Geofence receiver called"); Thread thread = new Thread() { public void run() { PushGeofenceEventTask pushGeofenceEventTask = new PushGeofenceEventTask(context, intent); Future<?> future = CTGeofenceTaskManager.getInstance().postAsyncSafely("PushGeofenceEvent", pushGeofenceEventTask); try { if (future != null) { future.get(BROADCAST_INTENT_TIME_MS, TimeUnit.MILLISECONDS); } } catch (TimeoutException e) { CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Timeout geofence receiver execution limit of 10 secs"); } catch (Exception e) { CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Exception while processing geofence receiver intent"); e.printStackTrace(); } if (result != null) { result.finish(); CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Geofence receiver Pending Intent is finished"); } } }; thread.start(); } catch (Exception e) { if (result != null) { result.finish(); CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Geofence receiver Pending Intent is finished"); } CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Exception while processing geofence receiver intent"); e.printStackTrace(); } CTGeofenceAPI.getLogger().debug(CTGeofenceAPI.GEOFENCE_LOG_TAG, "Returning from Geofence receiver"); }  @MainThread @Override void onReceive(final Context context, final Intent intent);  }
@Test public void testOnReceiveWhenIntentIsNull() { CTGeofenceReceiver receiver = new CTGeofenceReceiver(); CTGeofenceReceiver spy = Mockito.spy(receiver); spy.onReceive(application, null); verify(spy, never()).goAsync(); }
@Test public void testOnReceiveWhenIntentNotNull() { CTGeofenceReceiver receiver = new CTGeofenceReceiver(); CTGeofenceReceiver 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(); spy.onReceive(application, intent); await().until(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return isFinished[0]; } }); verify(pendingResult).finish(); }