Hello, espresso! Part 3 Working with intents π
Learn how to automate android intents (with and without stubbing) using espresso
Things are getting pretty exciting π as we work our way through learning espresso's API
In the last part Hello, espresso! Part 2 Working with lists, we learned how to work with list controls (RecyclerView
,Β AdapterView
) in espresso. Go ahead and have a read in case you missed it.
Learning to test Intents πͺ
In this post, we'll understand how to automate testing of intents using espresso.
espresso-intents
Β provides us the capabilities to validate intents for a couple of important use cases:
Test whether the correct intent is invoked with valid data by our app
Or, even stub out the intents sent out so that we can verify only our apps logic (while assuming other apps that we depend upon have been tested independently)
What is an Android intent?
InΒ developer.android.com's post about Android Intents
An intent is an abstract description of an operation to be performed.
It can be used:
withΒ
startActivity
Β to launch an Activity,
broadcastIntent
Β to send it to any interestedΒBroadcastReceiver
Β components,andΒ
Context.startService(Intent)
Β orΒContext.bindService(Intent, ServiceConnection, int)
Β to communicate with a background Service.
One of the use cases for whichΒ IntentsΒ are used a lot is toΒ launch ActivitiesΒ and they can be thought is a data structure that holds an abstract description of an action to be performed
There are 2 components to an Intent:
Action:Β What action has to be performed, some examples of this are:
ACTION_VIEW
Β displays data to the user, for instance, if we use it asΒtel: URI
Β it will invoke the dialer (we'll see this in our test example),ACTION_EDIT
Β gives explicit edit access to given data
Data:Β Data to operate on expressed as aΒ
Uri
You can read the full docΒ hereΒ to understand more about Intents
Understanding our App under test π΅π»
Let's start by understanding the app under test
We'll useΒ IntentsBasicSample
Β app, which has anΒ EditText
Β to enter a phone no and aΒ Button
Β to either call a number or randomly pick a no, if the user taps on the call number button it launches a dialer app
The below scenarios are possible
GIVEN user is on home screen
WHEN user taps on enter phone no EditText with id: @id/edit_text_caller_number
AND user types a valid phone no
AND user taps on call number Button with id: id @id/button_call_number
THEN the dialer activity is shown with entered phone no
I've written this in Gherkin syntax for clarity, however in a live test, the tests should always describe behavior and no be as procedural as i've written below. ReadΒ thisΒ page on cucumber website to understand more
Let's use Layout inspector to grab the selectors for the elements we want to work with:
Add required dependencies
We need to addΒ espresso-intents
Β dependency to ourΒ app/build.gradle
Β file as below, also itβs only compatible with espressoΒ 2.1+
Β and android testing lib versionΒ 0.3+
, so we need to double-check their versions in our dependencies as well
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.4.0'
androidTestImplementation 'androidx.test:runner :1.4.0'
androidTestImplementation 'androidx.test:rules:1.4.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
Test to launch a dialer activity using intents and validation
Below is the complete test to perform our scenario, don't worry π§π»ββοΈ if it does not make sense right now, we'll unpack this in detail below, the complete example is mentioned so that you can skim through its structure first before we dive deeper
@RunWith(AndroidJUnit4.class)
@LargeTest
public class DialerActivityPracticeTest {
public static final String VALID_PHONE_NUMBER = "123-456-7898";
@Rule
public GrantPermissionRule grantPermissionRule =
GrantPermissionRule.grant("android.permission.CALL_PHONE");
@Rule
public ActivityScenarioRule<DialerActivity> testRule =
new ActivityScenarioRule<>(DialerActivity.class);
@Before
public void setupIntents() {
// Initializes intents and begins recording intents, must be called before
// triggering any actions that call an intent that we want to verify with validation or stubbing
init();
}
@After
public void teardownIntents() {
// Clears intent state, must be called after each test case
release();
}
/** Test to enter a phone number and make a call and verify an intent is launched */
@Test
public void whenTapOnCallNumber_ThenOutgoingCallIsMade() {
// Type a phone no and close keyboard
Uri phoneNumber = Uri.parse("tel:" + VALID_PHONE_NUMBER);
onView(withId(R.id.edit_text_caller_number)).perform(typeText(VALID_PHONE_NUMBER), closeSoftKeyboard());
// Tap on call number button
onView(withId(R.id.button_call_number)).perform(click());
// Verify an intent is called with action and phone no and package
intended(allOf(hasAction(Intent.ACTION_CALL), hasData(phoneNumber)));
}
}
Setting up intents and permissions
Just likeΒ
Views
, we'll use JUnit rules to set up and tear down our intents before and after each test. We'll useΒActivityScenarioRule
Β for thisSince we want to automate theΒ
DialerActivity
Β class, we'll pass that as the generic type withinΒ<>
@Rule
public ActivityScenarioRule<DialerActivity> testRule =
new ActivityScenarioRule<>(DialerActivity.class);
βοΈHowever just adding the rule is not enough and we need to set up and tear down our intents before and after a test as well
We useΒ
@Before
Β andΒ@After
Β JUnit annotations for this purpose and callΒinit()
Β before our test starts to execute andΒrelease()
Β after the test has been executed
Note: If you read other blogs and even theΒ official google guide on espresso-intents, they show usage ofΒ
IntentsTestRule
Β for setting up intents, but this has recently been deprecated with suggestion to useΒActivityScenarioRule
Β withΒinit()
Β andΒrelease()
. I'm sure these examples and docs would get updated soon, you can meanwhile refer to this blog π. You can seeΒ this commitΒ to understand how your test code would look like prior and after this change.
@Before
public void setupIntents() {
// Initializes intents and begins recording intents, must be called before
// triggering any actions that call an intent that we want to verify with validation or stubbing
init();
}
@After
public void teardownIntents() {
// Clears intent state, must be called after each test case
release();
}
We also want our test to have permission to make a call and thus add the below snippet as another JUnit rule to ensure we don't get any permission errors during our test run
@Rule
public GrantPermissionRule grantPermissionRule = GrantPermissionRule.grant("android.permission.CALL_PHONE");
Writing core test logic
With that taken care of let's write our test
We store a test number in a static variable
public static final String VALID_PHONE_NUMBER = "123-456-7898";
We'll type the phone no into our EditText as below and then close the keyboard:
onView(withId(R.id.edit_text_caller_number)).perform(typeText(VALID_PHONE_NUMBER), closeSoftKeyboard());
We'll then tap the call number button
// Tap on call number button
onView(withId(R.id.button_call_number)).perform(click());
Asserting our intent was fired
Great ππΌ, we want to verify that our Intent was actually invoked and we can achieve that by usingΒ intended
Β method that takes an Intent matcher (either an existing one or one that we define).
Tip: π‘ You can refer toΒ Hamcrest TutorialΒ understand how hamcrest matchers work since we are going to use them heavily with espresso
// Verify an intent is called with action and phone no and package
intended(allOf(hasAction(Intent.ACTION_CALL), hasData(phoneNumber)));
If you notice, we useΒ allOf()
Β matcher, that checks that the examined object matchesΒ all of the specified matchers
We first check that theΒ intent
Β had the correct action by callingΒ hasAction(Intent.ACTION_CALL)
How do we know which action to assert? π€
We can look into app source inΒ DialerActivity
Β to understand more details about our intent
If you look atΒ createCallIntentFromNumber
Β method, you can see we create an intent with actionΒ Intent.ACTION_CALL
:
final Intent intentToCall = new Intent(Intent.ACTION_CALL);
Also, we see that we set a phone no as the intents data in:
intentToCall.setData(Uri.parse("tel:" + number));
Here is the full method for reference
private Intent createCallIntentFromNumber() {
final Intent intentToCall = new Intent(Intent.ACTION_CALL);
String number = mCallerNumber.getText().toString();
intentToCall.setData(Uri.parse("tel:" + number));
return intentToCall;
}
We also assert that our intent has the correct phone no set as data by:
Preparing the phone noΒ Uri
Β earlier
Uri phoneNumber = Uri.parse("tel:" + VALID_PHONE_NUMBER);
and then add the below line in ourΒ allOf
Β matcher
hasData(phoneNumber)
Stubbing intent response
If you run this test, you'll see the Dialer Activity pop up
In the above test, we saw how espresso intents could launch another activity and we can quickly validate them usingΒ intended
,
However, If we only care about testing the logic of our app and not so much about a 3rd party apps logic (since we anywaysΒ cannot manipulate the UIΒ of external activity, nor control theΒ ActivityResult
Β returned to the activity we are testing), then espresso allows us to stub intents and returns a mock response as well usingΒ intending
Let's see how we can do this:
We add the below line in ourΒ @Before
Β annotated setup method:
intending(not(isInternal()))
.respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
Let's understand its nuts and bolts:
We can configure espresso to return aΒ
RESULT_OK
Β for any intent call by usingΒisInternal()
Β intent matcher that checksΒ if an intents package is the same as the target package for the instrumentation test.Since in this case, we want to stub out all intent calls to other activities we can wrap this with aΒ
not()
Β so ensure we inverse the result of the matcher
We then ask espresso to return aΒ
RESULT_OK
Β as a stubbed response by usingΒrespondWith()
Β and mention the result we want to return:
.respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
Here:
Activity.RESULT_OK
Β is theΒresultCode
Β andnull
Β is the resultData since we don't want to return anything in the intent response
If we rerun the above test, you'll see that no dialer activity is started since the intent call to external activities is going to be stubbed
Test our own apps intent without making an external activity call a.k.a Stubbing response
Let's see another example of stubbing usingΒ intending
Β updated functional test flow
GIVEN user is on home screen
WHEN user taps on pick number Button with id: @id/button_pick_contact
THEN we check that an intent call was made
AND we verify intent response from Contacts Activity is stubbed
We can write the below test to achieve this flow:
@RunWith(AndroidJUnit4.class)
@LargeTest
public class DialerActivityPracticeTest {
public static final String VALID_PHONE_NUMBER = "123-456-7898";
@Rule
public GrantPermissionRule grantPermissionRule =
GrantPermissionRule.grant("android.permission.CALL_PHONE");
@Rule
public ActivityScenarioRule<DialerActivity> testRule =
new ActivityScenarioRule<>(DialerActivity.class);
@Before
public void setupIntents() {
// Initializes intents and begins recording intents, must be called before
// triggering any actions that call an intent that we want to verify with validation or stubbing
init();
}
@After
public void teardownIntents() {
// Clears intent state, must be called after each test case
release();
}
@Test
public void whenPickNumber_AndTapOnCallWithStub_ThenStubbedResponseIsReturned() {
// To stub all intents to contacts activity to return a valid phone number
// we use intending() and verify if component has class name ContactsActivity
// then we responding with valid result
intending(hasComponent(hasShortClassName(".ContactsActivity")))
.respondWith(
new Instrumentation.ActivityResult(
Activity.RESULT_OK, ContactsActivity.createResultData(VALID_PHONE_NUMBER)));
onView(withId(R.id.button_pick_contact)).perform(click());
onView(withId(R.id.edit_text_caller_number)).check(matches(withText(VALID_PHONE_NUMBER)));
}
}
In this example, we show that we could also selectively stub out intent calls to a particular activity, e.g. if we wanted all calls toΒ ContactsActivity
Β to return a code:Β RESULT_OK
Β and a valid phone no, we can do so by writing:
intending(hasComponent(hasShortClassName(".ContactsActivity")))
.respondWith(
new Instrumentation.ActivityResult(
Activity.RESULT_OK, ContactsActivity.createResultData(VALID_PHONE_NUMBER)));
Note: If we want to stub calls to all classes in a package we could use:Β
toPackage
Β method insideΒintending
intending(toPackage("com.android.contacts")).respondWith(result);
Here we useΒ hasComponent(hasShortClassName(".ContactsActivity"))
Β that matches any call to classΒ ContactsActivity
Β and respond withΒ RESULT_OK
, also we returnΒ resultData
Β as the return value ofΒ createResultData
Β method
If we see impl ofΒ createResultData
Β inΒ ContactsActivity
Β source code, we see it returns an empty intent with a phone no value
@VisibleForTesting
static Intent createResultData(String phoneNumber) {
final Intent resultData = new Intent();
resultData.putExtra(KEY_PHONE_NUMBER, phoneNumber);
return resultData;
}
We finally tap on the pick number button and verify that theΒ EditText
Β button has the same no as the one returned by the stubbed intent call
And that's how you automate intents with espresso! β
Resources
You can find the app and test code for this post on Github:
Please readΒ espresso-intentsΒ that talks about how to work with intents on Android developers
Refer to original source code onΒ testing-samples
Conclusion
Hopefully, this post gives you an idea of how to work with intents in espresso. Stay tuned for the next post where weβll dive into how to automate and work withΒ idling resourcesΒ with espresso
As always, Do share this with your friends or colleagues and if you have thoughts or feedback, Iβd be more than happy to chat over on Twitter or comments. Until next time. Happy Testing and learning.