How to check ACTION_SEND intent is started?

2019-05-14 08:08发布

问题:

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

回答1:

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