【问题标题】:android, how to unit test BroadcastReceiver which uses doAsync()android,如何对使用 doAsync() 的 BroadcastReceiver 进行单元测试
【发布时间】:2021-10-20 15:05:53
【问题描述】:

在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()时如何测试?

【问题讨论】:

    标签: unit-testing broadcastreceiver android-unit-testing


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-09-25
      • 2022-11-17
      • 1970-01-01
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 2019-11-02
      相关资源
      最近更新 更多