Question

My app uses standard simple sharing of text. In my test I want to check that my activity started the sharing intent. Is it possible?

I am using ActivityInstrumentationTestCase2 test.

Activity:

final Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share"));

Test:

final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SEND);
intentFilter.addDataType("text/plain");
final ActivityMonitor receiverActivityMonitor = getInstrumentation().addMonitor(
            intentFilter, null, false);

TouchUtils.clickView(this, getActivity().findViewById(R.id.share_button));
final Activity shareActivity = receiverActivityMonitor.waitForActivityWithTimeout(500);
assertNotNull(shareActivity); // Fails

The above test does not work. Is there a way to test that ACTION_SEND intent has started?

Temporary solution

For now, in activity I am saving intent to a member variable:

mSendIntent = new Intent();

So I can verify it from test:

assertEquals("android.intent.action.SEND", getActivity().mSharingIntent.getAction());
assertEquals("text/plain", getActivity().mSharingIntent.getType());
String sharedText = getActivity().mSharingIntent.getStringExtra(Intent.EXTRA_TEXT);
assertEquals("test I shared", sharedText);
Was it helpful?

Solution

You are passing the result of Intent.createChooser to startActivity, so you need to monitor Intent.ACTION_CHOOSER action.

final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_CHOOSER);
final ActivityMonitor receiverActivityMonitor = getInstrumentation().addMonitor(intentFilter, null, false);

TouchUtils.clickView(this, getActivity().findViewById(R.id.share_button));
final Activity shareActivity = receiverActivityMonitor.waitForActivityWithTimeout(500);
assertNotNull(shareActivity);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top