Curso De Testing Kotlin Patched -
src/ test/kotlin/ # Unit tests (run fast, no Android/Server) integrationTest/ # Integration tests (use real DB) testFixtures/ # Shared test data (factories, builders)
result.shouldBe(200) list.shouldContain("Kotlin") exception.shouldThrow<IllegalArgumentException> Kotlin Coroutines are amazing for production, but they are a nightmare for testing if you don't know the tricks. A naive test will pass when it should fail because the coroutine hasn't finished yet. The Golden Rule: runTest Never use Thread.sleep() in tests. Use kotlinx-coroutines-test .
@Test fun `fetchUser returns data after network call`() = runTest { val client = ApiClient() // This virtual time will skip the delay instantly. val user = client.fetchUser("123") assertEquals("John Doe", user.name) } } curso de testing kotlin
Did you find this "curso" useful? Share your biggest testing pain point in the comments below!
@Test fun `verify API is called only once`() = runTest { // 1. Create mock val api = mockk<MyApi>() // 2. Stub a suspend function (coEvery) coEvery { api.getData() } returns "Mocked Response" val repo = Repository(api) // 3. Execute val result = repo.refreshData() // 4. Verify (coVerify) coVerify(exactly = 1) { api.getData() } result shouldBe "Mocked Response" } } Traditional testing (Example-based) says: "Give input 2+2, check output 4." Property-based testing says: "For ALL integers, addition should be commutative." src/ test/kotlin/ # Unit tests (run fast, no
In this guide, we will move from basic JUnit setup to advanced property-based testing and coroutine simulation. Forget the old @Test annotations that feel clunky. Kotlin allows us to write tests that read like plain English. The Setup (Gradle) // build.gradle.kts dependencies { testImplementation("org.junit.jupiter:junit-jupiter:5.10.0") testImplementation("org.jetbrains.kotlin:kotlin-test-junit5") } The First Test: Clean Syntax Notice how we avoid assertThat(actual).isEqualTo(expected) (Hamcrest) or Assert.assertEquals() (JUnit). Instead, we use Kotlin's infix functions via the kotlin.test library.
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.delay class ApiClientTest { Use kotlinx-coroutines-test
@Test fun `state flow emits new values`() = runTest { val viewModel = MyViewModel() val collector = viewModel.stateFlow.test { viewModel.doAction("Click") // Await the next emission val item = awaitItem() assertEquals("Loading", item.status) // Ensure no extra items came cancelAndIgnoreRemainingEvents() } } A professional Kotlin project separates test sources by type:
