Custom context for sticky broadcasts with Robolectric

I'd like to test mine BroadcastReceiver

, which depends on sticky broadcasts, with Robolectric. Robolectric doesn't support sticky broadcasts by default, so I created my custom Context

one to make sticky broadcasts work like this:

public class MyContext extends MockContext {

    public MyContext() {
        super();
    }

    @Override
    public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
        if(receiver == null) { // A sticky broadcast was requested
            Intent request = new Intent();
            String action = filter.getAction(0);

            if(Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                request.putExtra(BatteryManager.EXTRA_PLUGGED, 1);
            } else if(Intent.ACTION_HEADSET_PLUG.equals(action)) {
                request.putExtra("state", 1); 
            }

            return request;
        }

        return super.registerReceiver(receiver, filter);
    }
}

      

My problem is what I should be using RuntimeEnvironment.application.getApplicationContext

to get a valid object Context

(I just tried just calling my custom constructor Context

, but that doesn't work). So how can I get a valid instance of my custom Context

or is this not possible with robolectric?

EDIT . Here is the code for my test and my BroadcastReceiver:

@Before
public void setup() {
    context = RuntimeEnvironment.application.getApplicationContext();
    receiver = new MyBroadcastReceiver(); // Create Receiver
}

@After
public void finish() {
    context.unregisterReceiver(receiver);
}

@Test
public void validateUsbChargingChange() {
    IntentFilter filter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
    context.registerReceiver(receiver, filter);

    // Simmulate SocketCharging by sending the corresponding Intent
    Intent chargingChange = new Intent("android.intent.action.ACTION_POWER_CONNECTED");
    RuntimeEnvironment.application.sendBroadcast(chargingChange);

    validatePreferences();
}

      

BroadcastReceiver:

@Override
public void onReceive(Context context, Intent intent) {
    IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent chargingIntent = appContext.registerReceiver(null, iFilter); // sticky
    int pluggedState = chargingIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

    boolean usbCharge = (pluggedState == BatteryManager.BATTERY_PLUGGED_USB);
    if(usbCharge) {  /* Write values to preferences */  }
}

      

+3


source to share





All Articles