gpt4 book ai didi

android - 使用 Robolectric 进行粘性广播的自定义上下文

转载 作者:行者123 更新时间:2023-12-05 07:43:46 27 4
gpt4 key购买 nike

我想用 Robolectric 测试我的 BroadcastReceiver,它依赖于粘性广播。默认情况下,Robolectric 不支持粘性广播,因此我创建了自定义 Context 以使粘性广播像这样工作:

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);
}
}

我的问题是我必须使用 RuntimeEnvironment.application.getApplicationContext 来获取有效的 Context 对象(我试图简单地调用我的自定义 的构造函数上下文 但这不起作用)。那么,我如何才能获得我的自定义 Context 的有效实例,或者使用 robolectric 是不可能的?

编辑:这是我的测试和 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();
}

广播接收器:

@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 */ }
}

最佳答案

您可以在测试类构造函数中显式发送StickBroadcast,如下所示

@RunWith(RobolectricTestRunner.class)
public class BatterySettingActivityTest {
{
ApplicationProvider.getApplicationContext().sendStickyBroadcast(new Intent(Intent.ACTION_BATTERY_CHANGED).putExtra(BatteryManager.EXTRA_LEVEL, 75).putExtra(BatteryManager.EXTRA_PLUGGED, 0));
}

@Rule
public ActivityScenarioRule<BatterySettingActivity> activityScenarioRule = new ActivityScenarioRule<>(BatterySettingActivity.class);


@Test
public void testStickBroadcast() {
activityScenarioRule.getScenario().onActivity(activity -> {
System.out.println("intentForStickyBroadcast=" + activity.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)));
});
}
}

关于android - 使用 Robolectric 进行粘性广播的自定义上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43415445/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com