Javier Manzano Javier Manzano - 1 year ago 98
Android Question

Is there any way to know if an activity has been started with Espresso?

I'm doing an Activity transition testing with Espresso but I don't know if this is the best way to do it:

public void testStartLogin() {

The last two are from the second activity but this looks horrible for me. Is there any different way?

Answer Source

Asserting something against a view that belongs to a certain activity is in my opinion a very elegant way of checking if that specific activity has been started. From the official docs:

At the same time, the framework prevents direct access to activities and views of the application because holding on to these objects and operating on them off the UI thread is a major source of test flakiness. Thus, you will not see methods like getView and getCurrentActivity in the Espresso API.

However, there is a way to accomplish what you need, like shown here. In my version, I also defined an assertion method like:

 public void assertCurrentActivityIsInstanceOf(Class<? extends Activity> activityClass) {
    Activity currentActivity = getActivityInstance();

which I used in the test methods.

For my own tests I didn't have any issues using it (Espresso 2.0 !), but it made it somewhat redundant since I would still check the views belonging to that activity. So it works, but I wouldn't recommend it.

Good luck!


There is also the possibility of checking if the intent was sent from your first activity to the second one (check this short tutorial), but that doesn't necessarily mean that the second activity displayed all of its views correctly. You should still check them being displayed, which brings you back to where you started.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download