curso de testing kotlin

Curso De: Testing Kotlin

@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."

@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: curso de testing kotlin

Kotest will automatically generate 1000 random pairs of integers (including negative, zero, positive) and run the test. If it fails, it the input to the smallest failing case. Module 6: Testing Flows & SharedFlows Testing StateFlow and SharedFlow requires collecting values in a controlled way. Use TestCollector or launchIn . @Test fun `verify API is called only once`()

import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull class CalculatorTest { Execute val result = repo

@Test fun `adding 2 and 3 should return 5`() { val result = Calculator().add(2, 3) assertEquals(5, result) // Or even nicer: assertNotNull(result) } }