Android UI Testing
with Espresso
Gary Cheng
KKBOX

Android automation
Espresso
• Introduce Espresso

• How to write Android UI testing

• The problems we met
Introduction
Simple Syntax onView( … )
.perform ( … )
.check ( … )
Reliability
main thread
Network response
idling resource 

v.s.

waiting mechanism
Run Faster
Appium / Espresso
Espresso Appium
Espresso Appium
Setup
Speed
Reliability
Use Services
login / logout
Service
onView( drawer ).perform( click )
onView( account ).perform( click )
onView( logoutButton ).perform( click )
KKBOXService.loginController.logout( )
UI
Source Code
Espresso
• Simple

• Faster

• Reliability

• Services
現況
Flaky Rate 2.3 %
How to Use Espresso
• setup

• syntax

• structure
Setup
Setup

Dependencies / Instrumentation Runner
Create Emulator
Open developer option
Disable animation
Syntax
onView( … )
.perform ( … )
.check ( … )
onView( ViewMatcher )
.perform ( … )
.check ( … )
ViewMatcher
• withId(…)

• withText(…)
onView( withId(…) )
.perform ( … )
.check ( … )
onView( withId(…) )
.perform ( ViewAction )
.check ( … )
ViewAction
• click( )

• scrollTo( )

• typeText( … )
onView( withId(…) )
.perform ( click( ) )
.check ( … )
onView( withId(…) )
.perform ( click( ) )
.check ( ViewAssertion )
ViewAssertion
• matches( … )

• doesNotExist( )
onView( withId( … ) )
.perform ( click( ) )
.check ( matches( … ) )
onView( playButton )
.perform ( click )
.check ( musicPlayed )
Structure
@Rule
annotaion
@Rule -> @Before -> @Test -> @After
@Rule -> @Before -> @Test -> @After
@Rule -> @Before -> @Test -> @After
@Rule -> @Before -> @Test -> @After
@Rule -> @Test
• setup

• syntax

• structure
Test Case 1
click count button will
plus 1
UI Automator Viewer

/Users/{user_name}/Library/Android/sdk/tools/bin
onView( withId( … ) )
.perform ( click( ) )
.check ( matches( … ) )
Recyclerview
onView( withId( … ) )
.perform ( RecyclerViewAction( … ) )
RecyclerViewAction
• actionOnItem( ViewMatcher, ViewAction )

• actionOnItemAtPosition( Position, ViewAction )
onView( withId( … ) )
.perform ( actionOnItem( … ) )
Test Case 2
Click animal item in the
list will show the animal
Test Case 3
Click item by position in
the list will show the
correct position info
Index
onView( withId( … ) )
.perform ( actionOnItemAtPosition( … ) )
• Normal case

• Recyclerview

• actionOnItem

• actionOnItemAtPosition
Problems
Problem 1
RecyclerViewAction can not scroll out the last views
Normal Case
Espresso
Why!!!
Just can't see the view
Solution 1
scroll a little more before click action
Custom ViewAction
Custom ViewAction
Custom ViewAction
Custom ViewAction
onView ( RecyclerView )

.perform ( actionOnItem ( 有聲書, customClick( ) ) )
Fix !!!!
Problem 2
Espresso only detect the UI thread
How about Idling
Resource
Solution 2
Implement waiting mechanism
waitForViewDisplayed
waitForViewDisplayed
• custom ViewAction

• waiting mechanism
Problems
Thank you

Android UI Testing with Espresso