简体   繁体   中英

How to send broadcast intent from instrumentation test

There are two applications which are run in background and communicate with each other using broadcast intents. Now, I need to create some instrumentation tests to cover communication functionality on device.

In tests I need, for example, to send a specific broadcast intent and check that broadcast receiver got it (compare got intent type in broadcast receiver with sent one, etc.)

The problem is that when I try to send broadcast , register broadcast receiver , etc. in @Test , I got:

cannot resolve method 'registerReceiver(com...MyBroadcastReceiver, com.content.IntentFilter) '

cannot resolve method 'sendBroadcast(com.content.Intent) '

...

What should I do to be able to use such functionality in instrumentation tests? Should test classes be inherited from some specific classes?

Thanks in advance!

registerReceiver() and sendBroadcast() are both methods of Context , so you'll need a Context instance to call them.

Take a look at the InstrumentationRegistry class.

Use its static getTargetContext() method to get ahold of the Context (so you can call your receiver methods on that instance).

For example:

InstrumentationRegistry.getTargetContext().sendBroadcast(someIntent);

If you're running your tests in Android API 26 or higher Context.sendBroadcast won't work. More information about broadcasts limitations here .

From android docs:

The LocalBroadcastManager.sendBroadcast method sends broadcasts to receivers that are in the same app as the sender. If you don't need to send broadcasts across apps, use local broadcasts.

This is how you can use LocalBroadcastManager in your instrumentation tests:

 val broadcastManager = LocalBroadcastManager.getInstance(InstrumentationRegistry.getInstrumentation().context)
 broadcastManager.sendBroadcast(intent)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM