Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test setResult() in an Android Espresso test?

Is there any good way to test the result code and data in an Android Espresso test? I am using Espresso 2.0.

Suppose I have an Activity called BarActivity.class, which upon performing some action, calls setResult(int resultCode, Intent data) with the appropriate payload.

I'd like to write a test case to verify the resultCode and data. However, because setResult() is a final method, I can't override it.

Some options I thought about were:

  • Define a new method like setActivityResult() and just use that so it can be intercepted, etc...
  • Write a test-only TestActivity that will call startActivityForResult() on BarActivity and check the result in TestActivity.onActivityResult()

Trying to think what's lesser of the two evils, or if there's any other suggestions on how to test for this. Any suggestions? Thanks!

like image 966
hiBrianLee Avatar asked May 06 '15 17:05

hiBrianLee


People also ask

How do you check espresso visibility?

One simple way to check for a View or its subclass like a Button is to use method getVisibility from View class. I must caution that visibility attribute is not clearly defined in the GUI world. A view may be considered visible but may be overlapped with another view, for one example, making it hidden.


1 Answers

If meanwhile you switched to the latest Espresso, version 3.0.1, you can simply use an ActivityTestRule and get the Activity result like this:

assertThat(rule.getActivityResult(), hasResultCode(Activity.RESULT_OK));
assertThat(rule.getActivityResult(), hasResultData(IntentMatchers.hasExtraWithKey(PickActivity.EXTRA_PICKED_NUMBER)));

You can find a working example here.

like image 147
Roberto Leinardi Avatar answered Sep 25 '22 15:09

Roberto Leinardi