Unit Testing with JUnit
Write fast, reliable unit tests with JUnit 4. Use @Test, @Before, @After, assertions, test LiveData with InstantTaskExecutorRule, and test coroutines with runTest.
Why Write Tests?
Tests are not a luxury — they are your safety net:
- Catch bugs before users do
- Refactor with confidence (if tests pass, nothing broke)
- Document intended behavior
- Prevent regressions when adding features
Well-tested code also tends to be better-designed code — if it's hard to test, the design is probably too tightly coupled.
Types of Android Tests
Two categories:
- Unit tests (
test/folder) — run on JVM, no device needed. Fast. Test plain Kotlin/Java logic. - Instrumented tests (
androidTest/folder) — run on a device or emulator. Slower. Test Android-specific code (Room DB, UI).
Prefer unit tests for business logic. Use instrumented only when you must interact with Android APIs.
All lessons in this course
- Unit Testing with JUnit
- Mocking with Mockito
- UI Testing with Espresso
- Debugging & Profiling