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.
@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." curso de testing kotlin
src/ test/kotlin/ # Unit tests (run fast, no Android/Server) integrationTest/ # Integration tests (use real DB) testFixtures/ # Shared test data (factories, builders) In this guide, we will move from basic
@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) } } The Setup (Gradle) // build