How to Do TDD in Android — Part 1: Overview and Setup
As we discussed in the previous article, unit tests are critical for development quality — and TDD forces you to write those tests before you write any production code. In this article we’ll look at how to configure an Android project for TDD.
Types of tests
Unit Tests
Unit tests sit at the base of the testing pyramid. They make your application solid and are fast to write.
Integration Tests
Integration tests occupy the second level of the pyramid. They verify that different modules of the application work correctly together.
UI Tests
UI tests verify that the application behaves visually as expected — that the right messages appear, the right screens load, and so on.
Types of tests in Android
Android gives you tools from both Google and third parties. There are two main categories:
Unit Tests — for testing small pieces of functionality (methods, classes, processes):
- JUnit — a simple framework for writing small, repeatable tests
- Robolectric — very popular for Android because it lets you run unit tests on the JVM without an emulator or physical device
Instrumentation / UI Tests — simulate real user interaction with the UI (tapping buttons, typing in EditTexts, etc.). These require an emulator or physical device:
Package structure for tests
Every Android project has two test package directories:
- test — unit tests that only need the JVM. No access to Android-specific components like
Context. - androidTest — instrumentation tests that need access to Android-specific components and require an emulator or physical device.
Project structure
For this project we’ll use the MVP design pattern (you can read more in the article on design patterns).
We’ll create a new project in Android Studio from the blank activity template, with the package name com.jamontes79.tdd_ejemplo and a single LoginActivity.
With this in place, we have everything ready to start writing tests — which we’ll get into in Part 3 of this series.
You can download the project at this stage from GitHub: https://github.com/jamontes79/TDD_Ejemplo/tree/c64f7df9ca81b7da1876cbf7011b74c7731a9fd1
Hope this is useful — see you in the next part.