RegistrationIntentService extends IntentService { @Override protected void onHandleIntent(Intent intent) { String token = tokenRetriever.getToken(); Intent registrationComplete = new Intent(ElloPreferences.REGISTRATION_COMPLETE); if(token != null) { registrationComplete.putExtra("GCM_REG_ID", token); sharedPreferences.edit().putBoolean(ElloPreferences.SENT_TOKEN_TO_SERVER, true).apply(); } else { sharedPreferences.edit().putBoolean(ElloPreferences.SENT_TOKEN_TO_SERVER, false).apply(); } sendBroadcast(registrationComplete); } RegistrationIntentService(); @Override void onCreate();  }
@Test public void testTokenReceived() { TokenRetriever tokenRetrieverMock = Mockito.mock(TokenRetriever.class); when(tokenRetrieverMock.getToken()).thenReturn("123456"); service.tokenRetriever = tokenRetrieverMock; service.onHandleIntent(serviceIntent); Boolean stored = sharedPreferences.getBoolean(ElloPreferences.SENT_TOKEN_TO_SERVER, false); assertTrue("Mark token sent to sever if token retrieved", stored); }
@Test public void testTokenNotReceived() { TokenRetriever tokenRetrieverMock = Mockito.mock(TokenRetriever.class); when(tokenRetrieverMock.getToken()).thenReturn(null); service.tokenRetriever = tokenRetrieverMock; service.onHandleIntent(serviceIntent); Boolean stored = sharedPreferences.getBoolean(ElloPreferences.SENT_TOKEN_TO_SERVER, true); assertFalse("Mark token NOT sent to sever if token NOT retrieved", stored); }
@Test public void testRegistrationCompleteBroadcastReceived() { TokenRetriever tokenRetrieverMock = Mockito.mock(TokenRetriever.class); when(tokenRetrieverMock.getToken()).thenReturn("123456"); service.tokenRetriever = tokenRetrieverMock; final String[] tokens = new String[1]; final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { tokens[0] = intent.getExtras().getString("GCM_REG_ID"); } }; service.registerReceiver(receiver, new IntentFilter(ElloPreferences.REGISTRATION_COMPLETE)); service.onHandleIntent(serviceIntent); assertEquals(tokens[0], "123456"); service.unregisterReceiver(receiver); }