Make your Espresso tests more fluent

Bartek Lipinski
AndroidPub
Published in
3 min readMar 15, 2017

If you ever tried writing Espresso tests by hand, you probably know the code can get pretty nasty, pretty quickly.

As long as you’re just matching views by their ids and performing a single action, everything looks nice and straightforward.

But when you try to do something more complicated, your code can lose a lot on its readability:

Cortado — can greatly reduce the method nesting needed for Espresso, leaving you the code that is more fluent and much easier to read:

Main purposes of the library are:

  1. Getting rid of Matchers.allOf(...)(use and() between your conditions)
  2. Getting rid of Matchers.anyOf(...)(use or() between your conditions)
  3. Getting rid of Matchers.not(...)(use not() before your condition)
  4. Allowing to perform a single action inline (e.g. use .perform().click() instead of .perform(ViewActions.click()))
  5. Keeping the interchangeability with Espresso where possible (so you can use e.g. Espresso.onView(Cortado.view().withId(R.id.example)).perform(ViewActions.click()))
  6. Providing a smart, fluent API (Cortado api is giving you choices only available at a particular stage of the chain).

Pay attention to the available methods:

Nothing has been specified yet. Setting conditions or negating the following condition are possible.
First condition has been specified (withId(R.id.example)), now you can only select and() or or().
After and() once again you can specify another condition or negate the following condition.
After not() you cannot call not() again, but you can specify the negated condition.
After the second condition you can only specify and() (as it has been previously chosen).

On top of all that, you don’t have to worry about Cortado not being able to work as good as Espresso in terms of the testing capabilities, because underneath, Cortado is Espresso. It just provides you with a bit nicer way to communicate with the framework, not modifying its operation at all.

I suggest you try Cortado the next time you write Android Instrumented Tests!

If you enjoyed this post, please show your support! Recommend, follow, comment, share.

This really means a lot!

--

--

Bartek Lipinski
AndroidPub

android engineer @whatnot | ex @reddit | ex @getthefabulous | recovering feature creep 💉 | https://github.com/blipinsk