We test repositories with fakes to check if our data handling works correctly without using real databases or network calls.
0
0
Repository testing with fakes in Android Kotlin
Introduction
When you want to test data fetching logic without connecting to a real server.
When you want to check how your app handles data storage without using a real database.
When you want fast tests that don't depend on external systems.
When you want to isolate repository logic from other parts of the app.
When you want to simulate different data scenarios easily.
Syntax
Android Kotlin
interface UserRepository {
suspend fun getUser(id: String): User?
}
class FakeUserRepository : UserRepository {
private val users = mutableMapOf<String, User>()
fun addUser(user: User) {
users[user.id] = user
}
override suspend fun getUser(id: String): User? {
return users[id]
}
}A FakeUserRepository implements the same interface as the real repository.
It stores data in memory for quick testing without real data sources.
Examples
This fake repository stores products in memory and returns them when requested.
Android Kotlin
interface ProductRepository {
suspend fun getProduct(id: String): Product?
}
class FakeProductRepository : ProductRepository {
private val products = mutableMapOf<String, Product>()
fun addProduct(product: Product) {
products[product.id] = product
}
override suspend fun getProduct(id: String): Product? {
return products[id]
}
}This version uses a fixed list of users instead of a mutable map.
Android Kotlin
class FakeUserRepository : UserRepository { private val users = listOf(User("1", "Alice"), User("2", "Bob")) override suspend fun getUser(id: String): User? { return users.find { it.id == id } } }
Sample App
This example shows a fake user repository storing users in memory. The test function adds users and fetches one by ID, printing the name.
Android Kotlin
data class User(val id: String, val name: String) interface UserRepository { suspend fun getUser(id: String): User? } class FakeUserRepository : UserRepository { private val users = mutableMapOf<String, User>() fun addUser(user: User) { users[user.id] = user } override suspend fun getUser(id: String): User? { return users[id] } } suspend fun testFakeRepository() { val fakeRepo = FakeUserRepository() fakeRepo.addUser(User("1", "Alice")) fakeRepo.addUser(User("2", "Bob")) val user = fakeRepo.getUser("1") println(user?.name ?: "User not found") } // To run testFakeRepository, use a coroutine scope or runBlocking in main
OutputSuccess
Important Notes
Fakes are simple and fast but do not test real database or network behavior.
Use fakes to isolate repository logic from external dependencies.
Remember to keep fake data realistic for better test coverage.
Summary
Repository testing with fakes helps test data logic without real data sources.
Fakes implement the same interface as real repositories but use in-memory data.
This approach makes tests faster and more reliable by avoiding external dependencies.