Unit Testing in Android
Unit Testing in Android
A unit test verifies the correctness of a single "unit" of code, usually a function, class, or small component, by isolating it from the rest of the system. In Android development, unit tests are typically used to check business logic, utility classes, or ViewModel behavior without involving the Android framework. They are fast, run on the local JVM without an emulator or device, and help detect bugs early. By the end of this lesson, you will be able to:
- Explain what a unit test is and why isolation from the Android framework matters.
- Write unit tests using JUnit with the Arrange Act Assert pattern.
- Set up unit test dependencies and directory structure in an Android project.
- Apply best practices for naming, isolation, and mocking.
- Distinguish between local unit tests and instrumented tests.
Basic Structure of a Unit Test
Unit tests in Android use JUnit 4 (or JUnit 5) as the test framework. Each test function is annotated with @Test and uses assertion methods to verify expected outcomes. The Arrange Act Assert (AAA) pattern provides a clear structure:
- Arrange: Set up the test data and environment.
- Act: Execute the behavior under test.
- Assert: Check if the outcome matches the expectation.
class Calculator {
fun add(a: Int, b: Int): Int = a + b
fun subtract(a: Int, b: Int): Int = a - b
}
import org.junit.Assert.assertEquals
import org.junit.Test
class CalculatorTest {
private val calculator = Calculator()
@Test
fun `adding two numbers returns correct result`() {
val result = calculator.add(2, 3)
assertEquals(5, result)
}
@Test
fun `subtracting two numbers returns correct result`() {
val result = calculator.subtract(5, 2)
assertEquals(3, result)
}
}
The @Test annotation marks a function as a test case. assertEquals(expected, actual) checks if the method returns the correct value. If the assertion fails, the test runner reports the expected and actual values.
Project Setup
Add the testing dependency in your module's build.gradle.kts:
dependencies {
testImplementation("junit:junit:4.13.2")
}
Unit test files are placed inside the src/test/java/ or src/test/kotlin/ directory. This is the local test source set that runs on the JVM without an Android device. The src/androidTest/ directory is reserved for instrumented tests that require a device or emulator.
This interview continues for subscribers
Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.
Become a Sponsor