In this guide
Android App Testing Explained: Unit Tests, Espresso and Fakes
Most student Android apps are tested the same way: by tapping through the app on a phone, finding a crash, fixing it, and tapping through again. That works until the app grows past a few screens. Then every change risks breaking something on a screen you did not re-check, and the demo-day crash comes from a path you stopped testing weeks ago. Automated tests are the fix: small checks that run themselves every time you build, so a broken change fails loudly in Android Studio instead of silently on the examiner's phone.
This guide explains the three kinds of Android test a student actually needs — unit tests, ViewModel tests with fakes, and Espresso UI tests — with short runnable examples in Kotlin, and the habits that keep a test suite useful instead of a chore.
Quick Answer
Android testing has three layers. Unit tests check one small piece of logic (a calculation, a validator, a formatter) in milliseconds with no phone or emulator. ViewModel tests check your screen logic against a fake repository, so they run fast and need no network. Espresso UI tests drive the real app on an emulator and check what the user actually sees. Write mostly unit tests, a few ViewModel tests, and a small number of Espresso tests for the critical flows — that ratio keeps the suite fast and the coverage where it matters.
The test pyramid: why the ratio matters
Picture a pyramid with three layers. The wide base is unit tests: cheap, fast, and numerous. The middle layer is integration tests — for a student app, usually ViewModel tests against a fake data source. The narrow top is UI tests: slow, fragile, and few. The shape is the point. A test that takes 50 milliseconds can run hundreds of times a day; a test that needs an emulator takes minutes and breaks when a layout id changes. If you invert the pyramid and test everything through the UI, the suite becomes so slow that you stop running it, and a test suite nobody runs is worse than no tests at all.
A practical target for a student project: a few dozen unit tests, a handful of ViewModel tests covering the main screens, and three to five Espresso tests covering the flows that must not break — login, the main list screen, and the one action your demo depends on. That is enough to catch the regressions that actually happen, without turning testing into a second project.
Unit tests: testing logic with no phone
A unit test checks one function in isolation. The best candidates are pure functions: given an input, they return an output, with no database, network or Android framework involved. Validators, formatters, price calculators and sorting logic are ideal.
Take a small example every student app has somewhere — a function that checks whether an Indian mobile number looks valid:
fun isValidMobile(number: String): Boolean {
val digits = number.filter { it.isDigit() }
return digits.length == 10 && digits[0] in '6'..'9'
}
The test for it lives in src/test/ (not src/androidTest/ — that folder is for tests that need a device) and reads like a list of examples:
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class MobileValidatorTest {
@Test
fun validNumber_passes() {
assertTrue(isValidMobile("9876543210"))
}
@Test
fun numberWithSpacesAndPrefix_passes() {
assertTrue(isValidMobile("+91 98765 43210"))
}
@Test
fun nineDigits_fails() {
assertFalse(isValidMobile("987654321"))
}
@Test
fun landlineStartingWithTwo_fails() {
assertFalse(isValidMobile("0221234567"))
}
}
Run it with the test task in Android Studio (right-click the test class, or the Gradle task testDebugUnitTest) and it finishes in well under a second. Four things to notice. First, each test checks one behaviour, and its name says which one. Second, the test includes the edge cases students actually get wrong — the +91 prefix, the leading zero, the too-short number. Third, the test does not need an emulator, a phone, or the app to launch. Fourth, when someone later "improves" the validator and breaks the +91 case, this test fails immediately, in the same build, instead of at demo time.
The discipline that makes unit tests valuable is writing them for logic you can break by accident. A function with two branches and no tests will be broken by a well-meaning edit within a month. A function with four tests will not — the tests catch the edit the same afternoon.
ViewModel tests: screen logic against a fake repository
Most real app logic lives in a ViewModel: load a list, handle a search query, save a form, show an error. Testing it directly is hard, because the real ViewModel talks to a real repository, which talks to a real database or API. The standard answer is a fake: a small in-memory stand-in for the repository that returns fixed data instantly.
Say your app shows a list of notes. The repository interface might be as simple as this:
interface NoteRepository {
suspend fun getNotes(): List<Note>
}
The ViewModel uses it and exposes the result as UI state:
class NotesViewModel(private val repository: NoteRepository) : ViewModel() {
private val _notes = MutableStateFlow<List<Note>>(emptyList())
val notes: StateFlow<List<Note>> = _notes
fun loadNotes() {
viewModelScope.launch {
_notes.value = repository.getNotes()
}
}
}
In the test, you pass a fake repository instead of the real one. The fake returns two hard-coded notes, so the test checks the ViewModel's behaviour — loading, exposing state — without any database:
class FakeNoteRepository : NoteRepository {
override suspend fun getNotes(): List<Note> = listOf(
Note(id = 1, title = "Buy resistors"),
Note(id = 2, title = "Solder the board")
)
}
class NotesViewModelTest {
@Test
fun loadNotes_exposesFakeNotes() = runTest {
val viewModel = NotesViewModel(FakeNoteRepository())
viewModel.loadNotes()
assertEquals(2, viewModel.notes.value.size)
assertEquals("Buy resistors", viewModel.notes.value[0].title)
}
}
Two details matter here. runTest is the coroutine test scope from kotlinx-coroutines-test: it runs the ViewModel's coroutine immediately, so the test does not need to wait for a real delay. And the fake lives in the test source set, so it never ships in the app. The same pattern covers error handling — write a second fake that throws, and check that the ViewModel exposes an error state instead of crashing.
This is the layer most student projects skip, and it is the layer that catches the most real bugs: a screen that shows stale data after a refresh, a loading spinner that never hides, an error that crashes instead of showing a message. All of those are ViewModel behaviours, and all of them are testable in milliseconds with a fake.
Espresso UI tests: checking what the user actually sees
UI tests drive the real app on an emulator: they tap buttons, type text, and check what appears on screen. Espresso is the framework, and its style reads almost like instructions to a user: find this view, do this action, check this result.
Suppose your app has a login screen with an email field, a password field and a button, and a welcome message appears after a successful login. The test looks like this:
@RunWith(AndroidJUnit4::class)
class LoginFlowTest {
@get:Rule
val activityRule = ActivityScenarioRule(MainActivity::class.java)
@Test
fun validLogin_showsWelcomeMessage() {
onView(withId(R.id.emailInput))
.perform(typeText("student@college.edu"), closeSoftKeyboard())
onView(withId(R.id.passwordInput))
.perform(typeText("correct-password"), closeSoftKeyboard())
onView(withId(R.id.loginButton)).perform(click())
onView(withText("Welcome back"))
.check(matches(isDisplayed()))
}
}
Espresso waits automatically for the app to become idle before each step, so you do not write sleep calls — and you should never write them: a fixed sleep is either too short on a slow emulator or a waste of time on a fast one. The test runs on a connected device or emulator from src/androidTest/, and it takes seconds to minutes, which is why you keep the count low.
Keep UI tests focused on flows, not details. Test that login works, that the list loads, that saving a note returns to the list. Do not test every validation message through the UI — that is what the unit tests are for. And give every test a stable target: match views by id or by content description, never by screen position, because a layout change should not break a test that checks behaviour.
Test doubles: fake vs mock vs stub
You will meet three words for stand-in objects. They are not interchangeable, and knowing which one you need saves confusion when reading documentation.
| Double | What it is | When to use it |
|---|---|---|
| Fake | A working, simplified version of the real thing (an in-memory repository) | Your default choice for repositories and data sources |
| Stub | Returns canned answers, nothing more | A dependency whose behaviour you need to control precisely |
| Mock | Records how it was called, so you can verify the calls | Checking that your code called a method, with what arguments, how often |
For student projects, fakes cover almost everything. A fake repository with two hard-coded items tests your ViewModel honestly and reads clearly. Reach for a mocking library like MockK only when you need to verify that a call happened — for example, that saving a note actually called the repository's save method exactly once. If you find yourself mocking everything, the design is usually the problem: code that is hard to test with a fake is often code with too many responsibilities.
Running tests and keeping them green
Tests only help if they run. Three habits make that automatic:
- Run the unit tests before every commit. In Android Studio, the test task is one click; in a terminal, the Gradle command is
./gradlew testDebugUnitTest. Make it part of the commit routine, the same as checking the app still launches. - Keep the suite fast. If the unit tests take more than a minute, something is wrong — usually a test that touches the network or the filesystem. Move that work behind a fake. A slow suite is a suite that stops being run.
- Fix a failing test the same day. A red test that everyone ignores teaches the team to ignore tests. Either the test is wrong, in which case fix the test, or the code is wrong, in which case fix the code. A test that stays red for a week is worse than no test, because it hides the next real failure behind the one you already know about.
When a test fails, read the failure message first. JUnit tells you which assertion failed and what the actual value was — that is usually enough to find the bug. The common causes, in order, are: the test is checking stale behaviour after a deliberate change (update the test), the code has a genuine regression (fix the code), or the test depends on the order tests run in (shared mutable state — give each test its own objects).
Common mistakes
- Testing through the UI what a unit test could check. Every validation rule tested only through Espresso costs minutes per run and breaks on layout changes. Push logic down into testable functions.
- No tests for the demo-critical path. The one flow your presentation depends on deserves a test more than any other part of the app. If login or the main list breaks, the demo fails, whatever else works.
- Sleep calls in UI tests. Espresso waits for idle on its own. A fixed sleep makes the suite slow and still flaky on a loaded machine.
- Testing the framework, not your code. A test that checks that a library method works is testing someone else's code. Test your logic: your validation, your state transitions, your error handling.
- Fakes that lie. A fake that returns data the real repository could never return gives you a passing test and a broken app. Keep the fake's data realistic — the same shapes, the same empty-list case, the same error the real source produces.
- One giant test that checks everything. When it fails, you learn nothing except that something, somewhere, broke. Small tests with clear names tell you exactly what broke.
FAQ
Do I need tests for a college project at all?
Not for the marks — most examiners never look at the test folder. You need them for yourself: they catch the regression you introduce the night before the demo, when you no longer have time to re-tap every screen by hand. A small suite is insurance, not ceremony.
How much coverage should I aim for?
For a student project, coverage of the logic that matters — validators, ViewModel state transitions, the demo-critical flows — is worth far more than a percentage number. Chasing 80% coverage usually means writing tests for getters and framework glue. Aim for every piece of logic you would be embarrassed to break.
Unit tests or UI tests first?
Unit tests first. They are faster to write, faster to run, and they catch the bugs that actually happen (wrong logic, missed edge cases). Add UI tests only for the two or three flows that must work end to end.
Can I test code that uses the Android framework, like Context or SharedPreferences?
Not in a plain unit test — those classes need a device. Either move the logic into a framework-free function and test that, or use Robolectric, which provides working shadows of Android classes on the JVM. Robolectric is the honest answer when the logic genuinely lives next to the framework; restructuring the code so the logic is testable is usually the better answer.
What about testing a Room database or Retrofit API?
Test the repository layer with a fake data source, as shown above. Testing the real database is a separate, slower kind of test — Room's in-memory database and Retrofit's MockWebServer exist for it, but for most student projects the fake is enough. The bugs that bite are in your logic, not in Room's query engine.
My tests pass on my machine but fail on my teammate's. Why?
Usually a shared-state problem: a test that writes to a file, a static counter, or a database that another test also uses, so the result depends on the order tests run in. Give each test its own objects, and never let tests share mutable state.
Limitations
This guide covers the testing a student Android project actually needs: unit tests for logic, ViewModel tests with fakes, and a small number of Espresso tests for critical flows. It does not cover screenshot testing, performance benchmarking, testing across many device sizes and Android versions, or the CI pipelines that run tests automatically on every push — those matter for a production app, and they are the natural next step once this guide's habits are in place. The code examples are minimal illustrations, not a complete test setup: real projects need the test dependencies in their Gradle file (JUnit, the coroutine test library, Espresso, and the AndroidX test runner) and a test source set that matches the project structure. Finally, tests prove your code does what your tests expect — they cannot prove the app is right for the user. Run the app yourself, on a real phone, before the demo.