vendredi 30 octobre 2015

Unit Testing Android SMS Receiver

i try to write an unit test on an BroadcastReceiver that gets informed when an SMS was received. Its not meant to be the default Application. Instead i just need this for an two factor authentication. For this case i created an PDU with [1].

But when i pass it down to the BroadcastReceiver the phone nr of the Sender never gets read by android it's just null. The body text is returned.

@TargetApi(Build.VERSION_CODES.KITKAT)
@Test
public void testOnReceive() throws Exception {
    final byte[] decodedPDU = BaseEncoding.base16().decode(PDU);
    final ReceiveSmsBroadcastReceiver receiveSmsBroadcastReceiver = spy(new ReceiveSmsBroadcastReceiver(true));
    final Intent intent = new Intent();
    intent.putExtra("format",SmsConstants.FORMAT_3GPP);
    intent.putExtra("pdus", new Object[]{decodedPDU});
    intent.setAction("android.provider.Telephony.SMS_RECEIVED");
    intent.putExtra(PhoneConstants.SUBSCRIPTION_KEY, 1);
    receiveSmsBroadcastReceiver.onReceive(InstrumentationRegistry.getTargetContext(), intent);

In the receiver i do this to get the SMSMessage Objects:

@TargetApi(Build.VERSION_CODES.KITKAT)
private void getSMSKitKat(final Context context, final Intent intent) {
    final SmsMessage[] messagesFromIntent = Telephony.Sms.Intents.getMessagesFromIntent(intent);

I receive an SmsMessage array here, the body message is correct. But i need to test my check sender phone number before i can notify the UI that the SMS is received: But nr is always null here:

private boolean isCorrectSender(@Nullable final SmsMessage message) {
    if (message == null) {
        return false;
    }
    final String nr = message.getOriginatingAddress();

Can someone point me whats wrong here ?

PS: SMSConstants and PhoneConstants are all framework classes i took from AOSP to get it running because those APIs are non public

[1] http://ift.tt/1OeaNlu

Aucun commentaire:

Enregistrer un commentaire