Espresso-Intents is an extension to Espresso, which enables validation and stubbing of Intents sent out by the application under test. It’s like Mockito, but for Android Intents.
- Make sure you have installed the Android Support Repository (see instructions).
- Open your app’s
build.gradlefile. This is usually not the top-level
Add the following line inside dependencies:
Espresso-Intents is only compatible with Espresso 2.1+ and the testing support library 0.3 so make sure you update those lines as well:
IntentsTestRule instead of
ActivityTestRule when using Espresso-Intents.
IntentsTestRule makes it easy to use Espresso-Intents APIs in functional UI tests. This class is an extension of
ActivityTestRule, which initializes Espresso-Intents before each test annotated with
@Test and releases Espresso-Intents after each test run. The activity will be terminated after each test and this rule can be used in the same way as
Espresso-Intents records all intents that attempt to launch activities from the application under test. Using the intended API (cousin of
Mockito.verify), you can assert that a given intent has been seen.
An example test that simply validates an outgoing intent:
Using the intending API (cousin of
Mockito.when), you can provide a response for activities that are launched with startActivityForResult (this is particularly useful for external activities since we cannot manipulate the user interface of an external activity nor control the
ActivityResult returned to the activity under test):
An example test with intent stubbing:
intended methods take a hamcrest
Matcher<Intent> as an argument. Hamcrest is library of matcher objects (also known as constraints or predicates). You have these options:
- Use an existing intent matcher: Easiest option, which should almost always be preferred.
- Implement your own intent matcher: Most flexible option (see the section entitled “Writing custom matchers” in the Hamcrest tutorial)
An example of intent validation with existing Intent matchers: