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 .
src/ test/kotlin/ # Unit tests (run fast, no Android/Server) integrationTest/ # Integration tests (use real DB) testFixtures/ # Shared test data (factories, builders)
Kotest has the best property testing implementation on the JVM. curso de testing kotlin
@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:
Whether you are building Android apps, backend services with Ktor or Spring Boot, or multi-platform libraries, Kotlin offers a unique set of tools to make testing not just bearable , but joyful . result
Use backticks to write sentences as test names. Your test reports will read like documentation. Module 2: The Game Changer – Kotest If you take only one thing from this curso , let it be Kotest . It is the flagship testing framework for Kotlin, replacing JUnit with a radically different syntax. Why Kotest? It supports Spec styles (BehaviorSpec, StringSpec, FreeSpec) and Property Testing out of the box. Example: The Behavior Spec class UserServiceTest : BehaviorSpec({ val service = UserService() given("A user with a valid email") { val email = "test@example.com" `when`("I call register") { val result = service.register(email) then("It should return a success message") { result shouldBe "User created" } and("The user should be stored in the DB") { service.exists(email) shouldBe true } } } }) Assertions: shouldBe vs shouldNotBe Kotest replaces assertEquals with infix functions:
// Real code class ApiClient { suspend fun fetchUser(id: String): User { delay(3000) // Simulate network return User("John Doe") } } Use kotlinx-coroutines-test
It’s time to change that. Welcome to your conceptual .