Search code examples
androidunit-testingandroid-pendingintent

Test PendingIntent send without sleep


I got the following test case:

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);

Is there a way to make this test pass without the Thread.sleep ?


Solution

  • You can use a CountDownLatch to wait on something like that to occur. You initialize it with a count. The await() methods will wait on the count to hit 0. When it does they stop blocking (or if you specify a timeout it will return false if it timed out before the count reached 0).

    Here's your sample code modified to use a 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));