An easy-to-start approach to TDD with Espresso

An easy-to-start approach to TDD with EspressoDmitry SiBlockedUnblockFollowFollowingJun 17A lot was written about the TDD approach, in essence, it relies on one assumption — your tests are fast.

If the tests are slow Red—Green—Refactor cycle is permanently stuck on the tests execution phase rather than on coding.

That also assumes that you do know how to write tests.

Many people try and give up because they’re not feeling productive, and it’s hard to keep doing something that slows and sacrifice the performance for some imaginary future stability or maintainability gain.

But what if there is a way to try TDD, even with slow UI tests, and still increase the productivity and the code coverage at the same time?The approach I adopted recently for Android Espresso tests helped me both keep practicing in tests writing, hence developing the skill, and ship faster with simple steps.

1.

Launch itEvery time I need to make a new screen in the app I start with an extremely minimalistic test that contains activity rule only.

So once I launch any test the activity starts, and that’s when I write the setup code of the activity.

That saves me the time I’d otherwise spend navigating to the new activity through the app.

2.

Design itOnce the activity is running I need a way to keep it on the screen to design the layout.

And here goes the infinite loop*.

The test itself is not executed in the application’s main thread, so it’s safe to sleep there and the application will keep working.

After every significant layout change, I relaunch the test.

(Yes, there is Instant Run but it’s not stable and the new version of the same feature is not available yet)3.

Test itNow when the layout is pretty and looks exactly as designed, I can wire the logic (which is ideally already covered with the proper unit-tests) and at the same time some minimalistic integration test that will serve as the guard rail in the future and validate some basic things like “Is the header visible?”, “Can user scroll?”, “Is submit button actually disabled by default?” which can not be validated by the unit tests.

That’s it!.The whole boilerplate is a mere 3 lines of code.

And the real tests are even less verbose with Kakao library and all view-access details isolated via the Page Object pattern.

Happy testing![*] in fact I even have the template in Android Studio that replaces word forever with `if (true) while(true) Thread.

sleep(100);` that works equally well with Kotlin and Java files without modifications.

.

. More details

Leave a Reply