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.
Unit Testing with JUnit is a free Android Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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.
JUnit 4 Setup
JUnit 4 is included by default in Android projects. Add these to app/build.gradle:
// app/build.gradle:
dependencies {
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3'
testImplementation 'androidx.arch.core:core-testing:2.2.0' // for LiveData
}Your First JUnit Test
Create a class in src/test/java/ and annotate test methods with @Test:
import org.junit.Test
import org.junit.Assert.*
class CalculatorTest {
private val calc = Calculator()
@Test
fun `addition returns correct sum`() {
val result = calc.add(2, 3)
assertEquals(5, result)
}
@Test
fun `division by zero throws exception`() {
assertThrows(ArithmeticException::class.java) {
calc.divide(10, 0)
}
}
}@Before and @After
Use lifecycle annotations to set up and tear down state around each test:
class UserRepositoryTest {
private lateinit var repo: UserRepository
private lateinit var fakeDao: FakeUserDao
@Before
fun setUp() {
fakeDao = FakeUserDao() // fresh instance before each test
repo = UserRepository(fakeDao)
}
@After
fun tearDown() {
fakeDao.clear() // clean up after each test
}
@Test
fun `getUsers returns all users`() {
fakeDao.insert(User(1, "Alice"))
fakeDao.insert(User(2, "Bob"))
assertEquals(2, repo.getUsers().size)
}
}Common Assertions
JUnit provides assertion methods in Assert.*:
// Equality:
assertEquals(expected, actual)
assertNotEquals(unexpected, actual)
// Null:
assertNull(value)
assertNotNull(value)
// Boolean:
assertTrue(condition)
assertFalse(condition)
// Same object reference:
assertSame(expected, actual)
// Custom message on failure:
assertEquals("User ID should be 1", 1, user.id)
// Exception:
assertThrows(IllegalArgumentException::class.java) {
User(id = -1, name = "")
}Testing a ViewModel
To test LiveData, add the InstantTaskExecutorRule so LiveData posts synchronously:
class UserViewModelTest {
@get:Rule
val instantTaskRule = InstantTaskExecutorRule()
private val fakeRepo = FakeUserRepository()
private lateinit var viewModel: UserViewModel
@Before
fun setUp() {
viewModel = UserViewModel(fakeRepo)
}
@Test
fun `users are loaded on init`() {
fakeRepo.usersToReturn = listOf(User(1, "Alice"), User(2, "Bob"))
viewModel.loadUsers()
val result = viewModel.users.value
assertNotNull(result)
assertEquals(2, result?.size)
}
}Testing Coroutines
Use TestCoroutineDispatcher / StandardTestDispatcher to control coroutine execution in tests:
class SyncWorkerTest {
@get:Rule
val instantTaskRule = InstantTaskExecutorRule()
private val testDispatcher = StandardTestDispatcher()
@Before
fun setUp() {
Dispatchers.setMain(testDispatcher)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `sync completes successfully`() = runTest {
val repo = FakeRepository()
val worker = SyncUseCase(repo, testDispatcher)
val result = worker.run()
assertTrue(result.isSuccess)
}
}Fake vs Mock
Two strategies for replacing real dependencies in tests:
- Fake — a working implementation designed for testing (e.g., an in-memory list instead of a real database). Easy to write, readable, no library needed.
- Mock — an auto-generated stub that records calls and lets you verify interactions (Mockito, MockK). More powerful, but can become brittle if overused.
Prefer Fakes for simple cases; use Mocks when you need to verify method calls.
Writing a Fake
A Fake implements the same interface as the real class but with in-memory storage:
interface UserDao {
fun getAll(): List<User>
fun insert(user: User)
}
class FakeUserDao : UserDao {
private val storage = mutableListOf<User>()
override fun getAll(): List<User> = storage.toList()
override fun insert(user: User) { storage.add(user) }
fun clear() { storage.clear() }
}Test Naming Convention
Good test names describe what is being tested and the expected outcome. Use backtick function names in Kotlin for readable descriptions:
`getUsers returns empty list when no users exist``login throws exception when password is blank``add returns correct sum for negative numbers`
Pattern: `subject does X when Y`
Quick Check
What is the purpose of @Before in a JUnit test class?
Recap: Unit Testing with JUnit
Reliable apps are tested apps:
- Unit tests go in
src/test/, run on JVM — fast - Annotate with
@Test, useassertEquals,assertTrue,assertThrows @Before/@Afterfor setup and teardownInstantTaskExecutorRulefor testing LiveData synchronouslyrunTest+StandardTestDispatcherfor coroutine testing- Prefer Fakes over Mocks for simple substitutions
Next: Mocking with Mockito for verifying interactions.
Frequently asked questions
Is the “Unit Testing with JUnit” lesson free?
Yes — the full text of “Unit Testing with JUnit” is free to read here on the web, and the Android Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.
What will I learn in “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. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Android Academy?
No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Unit Testing with JUnit” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Android Academy lesson?
Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Unit Testing with JUnit
- Mocking with Mockito
- UI Testing with Espresso
- Debugging & Profiling