Test that app launches another app in Android

2019-08-03 21:22发布

问题:

I have a very simple activity, that redirects the user to the app's Play Store page, when the button is clicked:

public class MyActivity extends AppCompatActivity {
    private static final String PLAY_STORE_URI =
        "market://details?id=" + BuildConfig.APPLICATION_ID;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.my_activity);
        findViewById(R.id.go_to_play_store).setOnClickListener(this::goToPlayStore);
    }

    public void goToPlayStore(View view) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(PLAY_STORE_URI));
        startActivity(intent);
    }
}

Is it possible to write a test to check that the PlayStore is launched when the button is clicked? Better, is it possible to verify it shows the expected page?

I know that by using ActivityMonitors transitions between Activities can be tested. I also know that I can verify the Intents being sent using Espresso Intents. But can I actually check that a user action launches another app?

回答1:

I would suggest a slightly different question - is it you app's job to verify that? You'd be testing not your own app but Android OS and Google's Play Store App.

The way I've been approaching it is by being explicit about the boundaries, and aware of the possible scenarios.

What I mean by that is, extract the Intent manipulation and invocation logic into a thin service (that's the being explicit about boundaries part) and test your Activity correctly interacts with it (by constructing the Intent appropriately).

The part about possible scenarios is being aware of what can happen. For example what does your app do (if anything) if the user doesn't have Play Store on their phone.



回答2:

I would click the button, then use:

intended(allOf(
    hasAction(Intent.ACTION_VIEW),
    hasData("https://play.google.com/store/apps/...your app...")
))