tezvyn:

JUnit on Android: Fast, Local Unit Tests

AI-drafted, machine-checkedSource: developer.android.combeginner
JUnit on Android: Fast, Local Unit Tests

JUnit on Android runs tests directly on your local machine's JVM, not a device, making them extremely fast. Use it for business logic and ViewModels that don't touch Android APIs. The footgun is trying to access framework code like `Context`, which will fail.

WHY IT EXISTS: Testing on a real device or emulator is slow. It involves compiling, packaging, deploying, and running the app for every test cycle. For pure logic that doesn't depend on the Android OS, this is massive overhead. Local unit tests were created to provide a near-instant feedback loop for the non-UI parts of an application.

THE MENTAL MODEL: JUnit on Android runs tests in a "local" environment: your computer's Java Virtual Machine (JVM). It's completely separate from any Android device or emulator. Imagine testing a calculator's add(2, 2) function. You don't need a phone screen to know the answer is 4. Local tests apply this principle to your app's business logic, running it as a standard Java program for maximum speed.

HOW IT WORKS: When you run a local unit test, typically located in the test/ source set of your module, the build system executes it using a standard JUnit test runner on your development machine's JVM. The test code can instantiate your app's classes and call their methods directly. It then asserts that the outputs match expectations. Because the Android framework JAR included in these tests contains only stubbed methods that throw exceptions, any call to a real Android API will cause the test to fail immediately.

WHEN TO USE IT: Use local JUnit tests for any code that has no dependency on the Android framework. This is ideal for testing ViewModels in MVVM (if they don't use Context), UseCases, Repositories (with fakes or mocks for data sources), and any utility or data transformation classes. The goal is to isolate and verify your business logic quickly.

WHEN NOT TO USE IT: Do not use local tests for anything that requires the Android framework or hardware. This includes UI interactions (clicking buttons), animations, permission requests, database access, or anything involving a Context. For these, you need instrumented tests, which run on a device or emulator.

ONE CANONICAL EXAMPLE: A simple example is testing a ViewModel that processes user input. A test could create an instance of the ViewModel, call a method like viewModel.onEmailChanged("test@example.com"), and then assert that a LiveData field viewModel.isEmailValid.value is now true. This entire interaction happens on the JVM without ever touching an Android UI component.

Read the original → developer.android.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.