Przejdź do treści
Biblioteka skilli
Programowanie · Testowanie

mobiai-android-testing

/mobiai-android-testing

Pomaga pisać i uruchamiać testy w projekcie Android, takie jak testy jednostkowe i interfejsu, oraz dobierać odpowiedni framework i wzorce.

Repozytorium
mobiai-core ↗
Licencja
MIT
Ostatnia zmiana repozytorium
21.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
1
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 21.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Pomaga pisać i uruchamiać testy w projekcie Android, takie jak testy jednostkowe i interfejsu, oraz dobierać odpowiedni framework i wzorce.

Oryginalny opis (EN)

Use when writing or running tests in an Android project — unit tests, UI tests, choosing the right framework and patterns.

Jak działa

  1. When to Use
  2. Test Types
  3. Unit Testing (JUnit + MockK)
  4. Compose UI Testing
  5. Espresso (XML Views)
  6. Running Tests
  7. Common Patterns
  8. Troubleshooting
Sekcje z nagłówków SKILL.md, w oryginale · 255 linii, 677 słów
Podgląd SKILL.md
---
name: mobiai-android-testing
description: Use when writing or running tests in an Android project — unit tests, UI tests, choosing the right framework and patterns.
license: MIT
compatibility: [claude-code, cursor, copilot, codex]
platforms: [android]
---

# Android Testing

Comprehensive guide to writing and running tests in Android projects.

## When to Use

- Writing unit tests for Android/Kotlin code
- Setting up test infrastructure
- Running and debugging test suites
- Choosing the right testing approach

## Test Types

| Type | Location | Framework | Speed | Uses Device |
|------|----------|-----------|-------|-------------|
| Unit | `src/test/` | JUnit + MockK | Fast | No |
| Integration | `src/test/` | JUnit + Robolectric | Medium | No (simulated) |
| UI / Instrumented | `src/androidTest/` | Espresso / Compose Testing | Slow | Yes |

## Unit Testing (JUnit + MockK)

### Setup

```kotlin
// build.gradle.kts
dependencies {
    testImplementation("junit:junit:4.13.2")
    testImplementation("io.mockk:mockk:1.13.12")
    testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
    testImplementation("app.cash.turbine:turbine:1.2.0") // For Flow testing
}
```

### File Location

Mirror the source path:
- Source: `app/src/main/java/com/example/feature/MyViewModel.kt`
- Test: `app/src/test/java/com/example/feature/MyViewModelTest.kt`

### Test Structure

```kotlin
class MyViewModelTest {

    @get:Rule
    val mainDispatcherRule = MainDispatcherRule()

    private val repository: MyRepository = mockk()
    private lateinit var viewModel: MyViewModel

    @Before
    fun setUp() {
        viewModel = MyViewModel(repository)
    }

    @Test
    fun `loadData sets state to Success when repository returns data`() = runTest {
        // Given
        val expected = listOf(Item("1", "Test"))
        coEvery { repository.getData() } returns expected

        // When
        viewModel.loadData()

        // Then
        assertEquals(UiState.Success(expected), viewModel.state.value)
        coVerify(exactly = 1) { repository.getData() }
    }

    @Test
    fun `loadData sets state to Error when repository throws`() = runTest {
        // Given
        coEvery { repository.getData() } throws IOException("Network error")

        // When
        viewModel.loadData()

        // Then
        assertTrue(viewModel.state.value is UiState.Error)
    }
}
```

### MainDispatcherRule (for ViewModel tests)

```kotlin
class MainDispatcherRule(
    private val dispatcher: TestDispatcher = UnconfinedTestDispatcher()
) : TestWatcher() {
    override fun starting(description: Description) {
        Dispatchers.setMain(dispatcher)
    }
    override fun finished(description: Description) {
        Dispatchers.resetMain()
    }
}
```

### MockK Cheat Sheet

```kotlin
// Create mock
val repo: Repository = mockk()
val repo: Repository = mockk(relaxed = true) // Returns defaults for unconfigured calls

// Stub behavior
every { repo.getData() } returns listOf(item)
coEvery { repo.fetchData() } returns result       // For suspend functions
every { repo.getData() } throws IOException()
every { repo.save(any()) } just runs               // Void functions

// Verify
verify { repo.getData() }
verify(exactly = 1) { repo.save(any()) }
coVerify { repo.fetchData() }
verify(exactly = 0) { repo.delete(any()) }         // Never called

// Capture arguments
val slot = slot<String>()
every { repo.search(capture(slot)) } returns emptyList()
// After call: slot.captured == "search term"

// Mock objects/companions
mockkObject(MySingleton)
every { MySingleton.instance } returns mockk()
```

### Flow Testing with Turbine

```kotlin
@Test
fun `events flow emits navigation event`() = runTest {
    viewModel.events.test {
        viewModel.onSubmitClicked()
        assertEquals(Event.NavigateToSuccess, awaitItem())
        cancelAndConsumeRemainingEvents()
    }
}
```

## Compose UI Testing

### Setup

```kotlin
dependencies {
    androidTestImplementation("androidx.compose.ui:ui-test-junit4")
    debugImplementation("androidx.compose.ui:ui-test-manifest")
}
```

### Test Structure

```kotlin
class MyScreenTest {
    @get:Rule
    val composeRule = createComposeRule()

    @Test
    fun submitButton_isDisabled_whenFieldIsEmpty() {
        composeRule.setContent {
            MyScreen(state = MyState(text = ""))
        }

        composeRule.onNodeWithText("Submit").assertIsNotEnabled()
    }

    @Test
    fun errorMessage_isDisplayed_whenStateIsError() {
        composeRule.setContent {
            MyScreen(state = MyState(error = "Something went wrong"))
        }

        composeRule.onNodeWithText("Something went wrong").assertIsDisplayed()
    }
}
```

## Espresso (XML Views)

```kotlin
@Test
fun clickSubmit_showsConfirmation() {
    onView(withId(R.id.btn_submit)).perform(click())
    onView(withText("Confirmed")).check(matches(isDisplayed()))
}
```

## Running Tests

```bash
# All unit tests
./gradlew testDebugUnitTest

# Specific flavor
./gradlew test<Flavor>DebugUnitTest

# Single test class
./gradlew testDebugUnitTest --tests "com.example.MyViewModelTest"

# Single test method
./gradlew testDebugUnitTest --tests "com.example.MyViewModelTest.loadData sets state to Success*"

# Instrumented tests (requires device/emulator)
./gradlew connectedDebugAndroidTest
```

## Common Patterns

### Testing Use Cases
```kotlin
@Test
fun `invoke returns transformed data`() = runTest {
    coEvery { repository.getItems() } returns rawItems
    val result = useCase()
    assertEquals(expectedTransformed, result)
}
```

### Testing Repository with Room
```kotlin
// Use in-memory database for tests
val db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build()
val dao = db.myDao()
```

### Testing Mapper/Converter Functions
```kotlin
@Test
fun `toEntity maps all fields correctly`() {
    val dto = MyDto(id = "1", name = "Test", value = 42.0)
    val entity = dto.toEntity()
    assertEquals("1", entity.id)
    assertEquals("Test", entity.name)
    assertEquals(42.0, entity.value, 0.001)
}
```

## Troubleshooting

### Tests pass locally but fail in CI
- Check timezone-dependent tests
- Check tests that depend on system locale
- Check flaky tests with `@FlakyTest` or increase timeouts

### MockK issues with final classes
Add to `src/test/resources/mockk-extensions/io.mockk.ifc`:
```
io.mockk.classmocking.enabled=true
```

### Coroutine test timing issues
Use `advanceUntilIdle()` or `runCurrent()` in `runTest` blocks.

Wersje

W bazie nie ma innych skilli o nazwie mobiai-android-testing.

Migawka bazy z 13.11.2026 · wersja paczki 2d7488e961af (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 1 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100mobiai-ios-testing
    Pomaga pisać i uruchamiać testy w projekcie iOS: jednostkowe, interfejsu i snapshotowe, oraz dobierać odpowiedni framework.
  • 100mobiai-write-tests
    Pisze testy dla kodu mobilnego, także testy regresji po zastosowaniu poprawki.
  • 100android-testing
    Pomaga pisać testy Android: jednostkowe, instrumentacyjne, Compose UI i zrzuty ekranu, a także diagnozować niestabilne testy.
  • 90Android Test
    Pisze i uruchamia testy jednostkowe i UI na Androidzie, także na telefonie, by sprawdzić ekran lub przepływ.
  • 100unit-testing
    Pisze i przegląda testy jednostkowe w projekcie Gather V2, a także pomaga w błędach testów i wzorcach testowania.
  • 90testing-craft
    Pomaga pisać, przeglądać i refaktoryzować testy oraz dobierać sposób weryfikacji zmiany w kodzie.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.