1package com.xtremelabs.robolectric.shadows; 2 3import android.content.BroadcastReceiver; 4import android.content.Context; 5import android.content.Intent; 6import android.content.IntentFilter; 7import android.support.v4.content.LocalBroadcastManager; 8import com.xtremelabs.robolectric.Robolectric; 9import com.xtremelabs.robolectric.WithTestDefaultsRunner; 10import org.junit.Test; 11import org.junit.runner.RunWith; 12 13import static junit.framework.Assert.*; 14 15@RunWith(WithTestDefaultsRunner.class) 16public class LocalBroadcastManagerTest { 17 private static LocalBroadcastManager lastInstance; 18 19 @Test 20 public void shouldGetInstance() throws Exception { 21 LocalBroadcastManager instance = LocalBroadcastManager.getInstance(Robolectric.application); 22 assertNotNull(instance); 23 assertSame(instance, LocalBroadcastManager.getInstance(Robolectric.application)); 24 } 25 26 @Test 27 public void shouldSendBroadcasts() throws Exception { 28 LocalBroadcastManager instance = LocalBroadcastManager.getInstance(Robolectric.application); 29 final boolean[] called = new boolean[1]; 30 final BroadcastReceiver receiver = new BroadcastReceiver() { 31 @Override 32 public void onReceive(Context context, Intent intent) { 33 called[0] = true; 34 35 } 36 }; 37 instance.registerReceiver(receiver, new IntentFilter("com.foo")); 38 39 instance.sendBroadcast(new Intent("com.bar")); 40 assertFalse(called[0]); 41 instance.sendBroadcast(new Intent("com.foo")); 42 assertTrue(called[0]); 43 } 44 45 @Test 46 public void shouldUnregisterReceiver() throws Exception { 47 48 LocalBroadcastManager instance = LocalBroadcastManager.getInstance(Robolectric.application); 49 final boolean[] called = new boolean[1]; 50 final BroadcastReceiver receiver = new BroadcastReceiver() { 51 @Override 52 public void onReceive(Context context, Intent intent) { 53 called[0] = true; 54 55 } 56 }; 57 instance.registerReceiver(receiver, new IntentFilter("com.foo")); 58 instance.unregisterReceiver(receiver); 59 instance.sendBroadcast(new Intent("com.foo")); 60 assertFalse(called[0]); 61 } 62 63 @Test 64 public void shouldResetStateBetweenTests1() throws Exception { 65 lastInstance = LocalBroadcastManager.getInstance(Robolectric.application); 66 assertNotNull(lastInstance); 67 } 68 69 @Test 70 public void shouldResetStateBetweenTests2() throws Exception { 71 assertNotNull(lastInstance); 72 assertNotSame(lastInstance, LocalBroadcastManager.getInstance(Robolectric.application)); 73 lastInstance = null; 74 } 75} 76