1

I've been writing some tests with Espresso to test a fragment.

My fragment has a broadcast receiver, and will update its views upon receiving broadcast events.

But I can't find a way to send a broadcast event that my tested fragment can receive.

Anyone having solution, or a better architecture to suggest?

I'm using 'com.android.support.test.espresso:espresso-core:2.2.2'

Footjy
  • 259
  • 1
  • 14

1 Answers1

3

I use CountDownLatch to wait for a broadcast. Here is my usage example:

@Test
public void waitForBroadcast() throws InterruptedException {
    final CountDownLatch gate = new CountDownLatch(1);
    final BroadcastReceiver br = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            gate.countDown();
        }
    };
    InstrumentationRegistry.getTargetContext().registerReceiver(br, new IntentFilter("broadcast.action.TO_WAIT"));
    gate.await(5, SECONDS);
    InstrumentationRegistry.getTargetContext().unregisterReceiver(br);
    assertThat("broadcast's not broadcasted!", gate.getCount(), is(0L));
}
KenIchi
  • 1,129
  • 10
  • 22
  • 1
    Thanks for your help. Today I feel this question is not relevant. I'm sorry I don't have time to test your code. It looks nice though. – Footjy May 21 '18 at 06:59
  • Maybe I'm not understanding your question correctly. But since I'm working on this thing and just want to share. Should [this question](https://stackoverflow.com/q/4805269/1562087) be more relevant perhaps? – KenIchi May 23 '18 at 00:21
  • I think you do understand the question, and I accepted your answer (just without testing it). Thanks. – Footjy May 23 '18 at 10:33
  • I'm not sure if this answer actually addresses the question (the question seems to be about sending a broadcast, while the answer is about waiting for a broadcast). However, I found the reported trick useful. – Franco Jul 13 '20 at 18:06
  • according to the question, you'll need some mechanism to leak the gate into the receiver (which resides in the Fragment), statics of DI?, it's best to guard it by some debug flag. – KenIchi Jul 14 '20 at 11:17
  • Oh you may want to look at the ResultReceiver together, optionally with a Latch, which can be embedded into the Fragment's argument or Intent, you can be notified from the Receiver side when it finishes by calling `send()` – KenIchi Jul 14 '20 at 11:22