我得到了以下测试用例:
Intent intent = new Intent("test");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("test");
testReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
recieved=true;
}
};
getContext().registerReceiver(testReceiver,intentFilter );
pendingIntent.send();
Thread.sleep(100);
assertTrue(recieved);
有没有办法在没有Thread.sleep的情况下让这个测试通过?
答案 0 :(得分:1)
您可以使用CountDownLatch等待类似的事情发生。你用计数初始化它。 await()方法将等待计数达到0.当它执行时它们会停止阻塞(或者如果指定超时,如果它在计数达到0之前超时,则返回false)。
以下是修改为使用CountDownLatch的示例代码:
CountIntent intent = new Intent("test");
PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("test");
final CountDownLatch countDownLatch = new CountDownLatch(1);
testReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
countDownLatch.countDown();
}
};
getContext().registerReceiver(testReceiver,intentFilter );
pendingIntent.send();
assertTrue(countDownLatch.await(1, TimeUnit.SECONDS));