Android JUnit测试BroadcastReceiver在abortBroadcast()上失败

时间:2013-11-30 11:49:00

标签: android junit broadcastreceiver

我开始为我的Android应用程序编写测试。它适用于大多数应用程序,但我有一个BroadcastReceiver用于处理传入的短信,接收器在某些情况下依次调用abortBroadcast()。这个小调用会导致测试用例失败,并出现以下异常:

java.lang.IllegalStateException: Call while result is not pending
at android.content.BroadcastReceiver.checkSynchronousHint(BroadcastReceiver.java:772)
at android.content.BroadcastReceiver.abortBroadcast(BroadcastReceiver.java:689)

我的测试用例现在看起来像这样:

public void testOnReceive() {
    Optional<byte[]> mockSmsWrapper = TestUtils.createMockSms(getContext(), sender, body);

    if (mockSmsWrapper.isPresent()) {
        SmsReceiver receiver = new SmsReceiver();
        Intent intent = new Intent();
        intent.putExtra("pdus", new Object[] { mockSmsWrapper.get() });
        intent.setType("vnd.android-dir/mms-sms");      
        receiver.onReceive(getContext(), intent);

        //TODO: Verify results!
    }
}

我想知道Context是否存在问题,某些数据未设置为意图(因此Call while result is not pending)或是否甚至可以测试abortBroadcast()

还应该添加我的TestClass扩展AndroidTestCase

谢谢!

1 个答案:

答案 0 :(得分:0)

您的结果是因为直接调用onReceive方法。

相反,您应该执行以下操作:

Intent intent = new Intent("android.provider.Telephony.SMS_RECEIVED");
intent.putExtra("pdus", new Object[] { mockSmsWrapper.get() });
intent.setType("vnd.android-dir/mms-sms");

PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,intent ,PendingIntent.FLAG_ONE_SHOT);
try {
    pendingIntent.send(0);
} catch (CanceledException e) {
    Log.e(YourClass.class.getSimpleName(), android.util.Log.getStackTraceString(e));
}
Thread.sleep(2000);
//Verify result