[英]android, how to unit test BroadcastReceiver which uses doAsync()
on android app, using Broadcastreceiver to handle the notification click.在 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) {}
}
}
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.但它抛出异常,因为
asyncResult
为空。
How to test when it uses doAsync()?如何测试何时使用 doAsync()?
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.