1package com.xtremelabs.robolectric.shadows; 2 3import static com.xtremelabs.robolectric.Robolectric.newInstanceOf; 4import static com.xtremelabs.robolectric.Robolectric.shadowOf; 5import static org.hamcrest.CoreMatchers.is; 6import static org.junit.Assert.assertThat; 7 8import org.junit.Test; 9import org.junit.runner.RunWith; 10 11import android.app.Service; 12import android.appwidget.AppWidgetProvider; 13import android.content.Intent; 14import android.content.IntentFilter; 15import android.content.ServiceConnection; 16import android.media.MediaScannerConnection; 17import android.os.IBinder; 18 19import com.xtremelabs.robolectric.Robolectric; 20import com.xtremelabs.robolectric.WithTestDefaultsRunner; 21 22@RunWith(WithTestDefaultsRunner.class) 23public class ServiceTest { 24 25 @Test(expected = IllegalStateException.class) 26 public void shouldComplainIfServiceIsDestroyedWithRegisteredBroadcastReceivers() throws Exception { 27 MyService service = new MyService(); 28 service.registerReceiver(new AppWidgetProvider(), new IntentFilter()); 29 service.onDestroy(); 30 } 31 32 @Test 33 public void shouldNotComplainIfServiceIsDestroyedWhileAnotherServiceHasRegisteredBroadcastReceivers() throws Exception { 34 MyService service = new MyService(); 35 36 MyService service2 = new MyService(); 37 service2.registerReceiver(new AppWidgetProvider(), new IntentFilter()); 38 39 service.onDestroy(); // should not throw exception 40 } 41 42 @Test 43 public void shouldUnbindServiceSuccessfully() { 44 MyService service = new MyService(); 45 ServiceConnection conn = Robolectric.newInstanceOf(MediaScannerConnection.class); 46 service.unbindService(conn); 47 } 48 49 @Test (expected=IllegalArgumentException.class) 50 public void shouldUnbindServiceWithExceptionWhenRequested() { 51 MyService service = new MyService(); 52 shadowOf(service).setUnbindServiceShouldThrowIllegalArgument(true); 53 54 ServiceConnection conn = newInstanceOf(MediaScannerConnection.class); 55 service.unbindService(conn); 56 } 57 58 @Test 59 public void stopForeground() { 60 MyService service = new MyService(); 61 service.stopForeground(true); 62 63 ShadowService shadowService = shadowOf(service); 64 assertThat(shadowService.isForegroundStopped(), is(true)); 65 assertThat(shadowService.getNotificationShouldRemoved(), is(true)); 66 } 67 68 private static class MyService extends Service { 69 @Override public void onDestroy() { 70 super.onDestroy(); 71 } 72 73 @Override public IBinder onBind(Intent intent) { 74 return null; 75 } 76 } 77} 78