In this post we will cover what is Espresso, What api espresso provided, How to write UI test.

So far in the journey, in Why developers are scared to refactor code , Part 1 , Part 2 & part 3 of this series, we gained why TDD is supreme, types of testing in android, where to place tests, how to write, run tests , what is mocking, how to verify is method is called etc.

What is Espresso ?

Espresso is testing framework by google for UI testing. It provides API’s for UI testing in single application. UI test ensures that user don’t have poor interaction or encounter unexpected behaviour.

I know you are now used to write test for your code(at-least that is my expectation from you😉).

Espresso mainly 3 collection

ViewMatcher: is used to locate the view on UI using onView() ViewActions: is user to preform action on UI element using ViewInteraction.perform() ViewAssertion: is used to assert view using ViewInteraction.check()

onView(withId(R.id.my_view))// withId(R.id.my_view) is a ViewMatcher

.perform(click()) // click() is a ViewAction

.check(matches(isDisplayed())); // matches(isDisplayed()) is a ViewAssertion

You can find Espresso cheat sheet on official site



press SHIFT+CTRL+T on LoginActivity and create test class for UI testing in androidTest folder.

After creating @RunWith(AndroidJUnit4.class) on class name

Now we write test checkUserNameEditTextIsDisplayed() with @Test annotation. We also need ActivityTestRule

In checkUserNameEditTextIsDisplayed() we are checking is user name EditText is displayed on UI.

Espresso methods are self explanatory.

Run the test it will pass(For running test we need emulator or actual device as this is UI test ).

Now try making visibility of user edit text to gone and again run the test it fails.

Now we test click on login button for empty fields and check if error message is displayed or not.

Run test it is passing .

Next we are going to write test for login success.

Run the test it is passing.

Cheers!!!🍺🍺🍺. We have completed basic of testing. There is lot more to explore in testing.

Would like to hear your suggestion, inputs on this series or post

If you like the series about TDD please recommend it to other as well.

For more update please follow me on Medium.

Thanks to all reader.

Thanks to people who helped or encouraged me while writing this post

Nikhil Narkhedkar (Reviewer), Shrikant Ekde(Reviewer), Maheshwar Ligade, Varsha Nehatrao, Chaitanya Deshpande & Amol Bombe.

People who added value to series

Keith Ensign , Marlon López , Alexander Pletnev.

Links form where I took references

You can reach me at nlshjarad7@gmail.com

You can find complete code for this series

Gently Press the ♡(empty) and make it ❤️(filled).