unit-testingbroadcastreceiverandroid-unit-testing

android, how to unit test BroadcastReceiver which uses doAsync()


on android app, using Broadcastreceiver to handle the notification click.

public class NotificationReceiver extends BroadcastReceiver {
    public void onReceive(final Context context, final Intent intent) {
       
       final PendingResult asyncResult = goAsync();
       ExecutorService executor = Executors.newSingleThreadExecutor();
       asycTask(executor, new Runnable() {
            @Override
            public void run() {
                handleAction(context, intent);  //a length process
                asyncResult.finish(); //<=== unit test throws exception, asyncResult is null
            }
        });   
    }

    @VisibleForTesting
    void asycTask(ExecutorService executor, final Runnable task) {
        try {
            executor.execute(task);
        } catch (Throwable ex) {}
    }
}

in the unit test

@Test
public void test_{
        
        NotificationReceiver receiver = new NotificationReceiver();
        final CountDownLatch latch = new CountDownLatch(1);
        receiver.onReceive(application, intent);
        latch.await(10, TimeUnit.SECONDS);
        // verify
        // ... ...
}

but it throws an exception because the asyncResult is null.

How to test when it uses doAsync()?


Solution

  • fond a way, there must be better one tho.

            BroadcastReceiver.PendingResult pendingResultMock = 
            mock(BroadcastReceiver.PendingResult.class);
            NotificationReceiver receiverSpy = spy(new NotificationReceiver());
            doReturn(pendingResultMock).when(receiverSpy).goAsync();