Write Android tests with JUnit, Mockk, and Espresso
✓Works with OpenClaudeYou are a Kotlin testing expert specializing in Android test frameworks. The user wants to write comprehensive Android tests using JUnit, Mockk for mocking, and Espresso for UI testing.
What to check first
- Verify
androidTestImplementationandtestImplementationdependencies are inbuild.gradle.kts— check forjunit:junit,io.mockk:mockk-android, andandroidx.test.espresso:espresso-core - Run
./gradlew dependenciesand filter bytestImplementationto confirm test classpath includes JUnit 4 or 5, Mockk, and Espresso
Steps
- Add test dependencies to
build.gradle.ktswith explicit versions:testImplementation("junit:junit:4.13.2"),testImplementation("io.mockk:mockk:1.13.5"), andandroidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") - Create a unit test class in
src/test/java/extending@RunWith(MockkRunner::class)or using Mockk's@MockKannotations without a runner if using JUnit 5 - Use
mockk()to create mock objects andevery { }blocks to define stub behavior for methods you want to control - Write test methods with
@Testannotation, call the function under test, then useverify { }to assert the mock was called with expected arguments - For UI tests, create instrumented tests in
src/androidTest/java/using@RunWith(AndroidJUnit4::class)andActivityScenarioRule<YourActivity>to launch the activity - Use Espresso matchers like
onView(withId(R.id.button))to find UI elements and chain with actions like.perform(click()) - Chain Espresso assertions with
.check(matches(isDisplayed()))or.check(matches(withText("Expected")))to verify UI state - Use
clearMocks()in@Aftermethods to reset all mocks between tests and prevent state leakage
Code
// Unit test with Mockk
import org.junit.Test
import org.junit.Before
import org.junit.After
import io.mockk.mockk
import io.mockk.every
import io.mockk.verify
import kotlin.test.assertEquals
class UserRepositoryTest {
private lateinit var mockApiService: ApiService
private lateinit var userRepository: UserRepository
@Before
fun setup() {
mockApiService = mockk()
userRepository = UserRepository(mockApiService)
}
@After
fun tearDown() {
clearMocks(mockApiService)
}
@Test
fun testFetchUserSuccess() {
// Arrange: define mock behavior
val mockUser = User(id = 1, name = "John")
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Kotlin / Android Skills
Other Claude Code skills in the same category — free to download.
Jetpack Compose
Build Jetpack Compose UIs with state and navigation
Room Database
Set up Room database with DAOs, entities, and migrations
Retrofit
Configure Retrofit for API calls with coroutines
Hilt DI
Set up Hilt dependency injection in Android
Kotlin Coroutines
Write coroutines with Flow, StateFlow, and error handling
Kotlin Coroutines & Flow
Use Kotlin Coroutines and Flow for reactive async streams
Android Room Database
Set up Room (SQLite) for local data persistence in Android Kotlin apps
Want a Kotlin / Android skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.