TE

Kotlin Testing

Kotlin testing conventions with JUnit 5, MockK, coroutine test utilities, and KoTest matchers

Details

Language / Topic
kotlinKotlin
Category
Testing

Rules

balanced
- Follow Arrange-Act-Assert pattern. Use backtick function names for readable test names: `` `should return error when user not found` ``.
- Each test should verify one behavior. Keep tests focused and independent.
- Use `kotlin.test` annotations (`@Test`, `assertEquals`) or JUnit 5 with Kotlin extensions — use MockK for Kotlin-idiomatic mocking.
- Name tests with backticks for readable sentences: `` @Test fun `returns 404 when user does not exist`() {} `` — JUnit 5 on the JVM accepts backtick function names.
- Use `MockK` for Kotlin-idiomatic mocking: `val repo = mockk<UserRepository>(); every { repo.findById(any()) } returns null` — use `coEvery` / `coVerify` for suspend functions.
- Use `runTest` from `kotlinx-coroutines-test` to test suspend functions: `@Test fun `fetches user` () = runTest { val result = service.getUser(id); assertEquals(expected, result) }`.
- Use `@ParameterizedTest` with `@MethodSource` for data-driven tests: `@MethodSource("invalidEmails") @ParameterizedTest fun `rejects invalid email`(email: String) { ... }`.
- Use nested `@Nested` classes to group tests by scenario: `@Nested inner class WhenUserExists { ... }` — improves test output readability.