0

在 android 应用上,使用 Broadcastreceiver 处理通知点击。

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

在单元测试中

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

但它抛出一个异常,因为它asyncResult是空的。

如何测试它何时使用 doAsync()?

4

1 回答 1

0

喜欢一种方式,一定有更好的方式。

        BroadcastReceiver.PendingResult pendingResultMock = 
        mock(BroadcastReceiver.PendingResult.class);
        NotificationReceiver receiverSpy = spy(new NotificationReceiver());
        doReturn(pendingResultMock).when(receiverSpy).goAsync();
于 2021-10-20T17:11:46.863 回答