본문으로 건너뛰기
Skillpedia
테스트280k · #197

kotlin-testing

하는 일

이 스킬은 Kotlin으로 작성한 코드의 테스트를 만들도록 돕습니다. Kotest와 MockK 같은 도구를 사용해 코드가 올바르게 작동하고 유지보수하기 쉬운지 확인합니다.

사용하는 경우

  • ✓Kotlin 코드의 새 부분을 작성할 때.
  • ✓기존 Kotlin 코드에 테스트를 추가할 때.
  • ✓커버리지 보고서로 코드 품질을 확인하고 싶을 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/kotlin-testing/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/kotlin-testing/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“Kotlin에서 이메일 주소를 검증하는 함수의 테스트는 어떻게 작성하나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

이 스킬은 먼저 실패하는 테스트(RED)를 작성하게 합니다. 그다음 테스트를 통과시키는 최소한의 코드(GREEN)를 작성하고, 마지막으로 테스트가 계속 통과하는 상태에서 코드를 더 깔끔하게 정리하도록 안내합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Kotlin Testing Patterns

Comprehensive Kotlin testing patterns for writing reliable, maintainable tests following TDD methodology with Kotest and MockK.

When to Use

  • Writing new Kotlin functions or classes
  • Adding test coverage to existing Kotlin code
  • Implementing property-based tests
  • Following TDD workflow in Kotlin projects
  • Configuring Kover for code coverage

How It Works

  1. Identify target code — Find the function, class, or module to test
  2. Write a Kotest spec — Choose a spec style (StringSpec, FunSpec, BehaviorSpec) matching the test scope
  3. Mock dependencies — Use MockK to isolate the unit under test
  4. Run tests (RED) — Verify the test fails with the expected error
  5. Implement code (GREEN) — Write minimal code to pass the test
  6. Refactor — Improve the implementation while keeping tests green
  7. Check coverage — Run ./gradlew koverHtmlReport and verify 80%+ coverage

Examples

The following sections contain detailed, runnable examples for each testing pattern:

Quick Reference

TDD Workflow for Kotlin

The RED-GREEN-REFACTOR Cycle

RED     -> Write a failing test first
GREEN   -> Write minimal code to pass the test
REFACTOR -> Improve code while keeping tests green
REPEAT  -> Continue with next requirement

Step-by-Step TDD in Kotlin

// Step 1: Define the interface/signature
// EmailValidator.kt
package com.example.validator

fun validateEmail(email: String): Result<String> {
    TODO("not implemented")
}

// Step 2: Write failing test (RED)
// EmailValidatorTest.kt
package com.example.validator

import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.result.shouldBeFailure
import io.kotest.matchers.result.shouldBeSuccess

class EmailValidatorTest : StringSpec({
    "valid email returns success" {
        validateEmail("user@example.com").shouldBeSuccess("user@example.com")
    }

    "empty email returns failure" {
        validateEmail("").shouldBeFailure()
    }

    "email without @ returns failure" {
        validateEmail("userexample.com").shouldBeFailure()
    }
})

// Step 3: Run tests - verify FAIL
// $ ./gradlew test
// EmailValidatorTest > valid email returns success FAILED
//   kotlin.NotImplementedError: An operation is not implemented

// Step 4: Implement minimal code (GREEN)
fun validateEmail(email: String): Result<String> {
    if (email.isBlank()) return Result.failure(IllegalArgumentException("Email cannot be blank"))
    if ('@' !in email) return Result.failure(IllegalArgumentException("Email must contain @"))
    val regex = Regex("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$")
    if (!regex.matches(email)) return Result.failure(IllegalArgumentException("Invalid email format"))
    return Result.success(email)
}

// Step 5: Run tests - verify PASS
// $ ./gradlew test
// EmailValidatorTest > valid email returns success PASSED
// EmailValidatorTest > empty email returns failure PASSED
// EmailValidatorTest > email without @ returns failure PASSED

// Step 6: Refactor if needed, verify tests still pass

Kotest Spec Styles

StringSpec (Simplest)

class CalculatorTest : StringSpec({
    "add two positive numbers" {
        Calculator.add(2, 3) shouldBe 5
    }

    "add negative numbers" {
        Calculator.add(-1, -2) shouldBe -3
    }

    "add zero" {
        Calculator.add(0, 5) shouldBe 5
    }
})

FunSpec (JUnit-like)

class UserServiceTest : FunSpec({
    val repository = mockk<UserRepository>()
    val service = UserService(repository)

    test("getUser returns user when found") {
        val expected = User(id = "1", name = "Alice")
        coEvery { repository.findById("1") } returns expected

        val result = service.getUser("1")

        result shouldBe expected
    }

    test("getUser throws when not found") {
        coEvery { repository.findById("999") } returns null


…
자주 묻는 질문

TDD란 무엇인가요?

TDD는 테스트 주도 개발(Test-Driven Development)의 약자입니다. 본 코드를 작성하기 전에 테스트를 먼저 작성하는 개발 방법론입니다.

Kotest와 MockK는 무엇인가요?

Kotest와 MockK는 Kotlin에서 많이 쓰는 라이브러리입니다. Kotest는 테스트를 체계적으로 작성하도록 돕고, MockK는 코드의 일부를 흉내 내어 원하는 부분만 테스트할 수 있게 해 줍니다.

‘코드 커버리지’란 무엇인가요?

테스트가 실행한 코드가 전체 코드의 몇 퍼센트인지를 보여 주는 지표입니다. 커버리지가 높을수록 대부분의 코드가 테스트되었다는 뜻입니다.

상세 정보

작성자의 원본 설명

Kotlin testing patterns with Kotest, MockK, coroutine testing, property-based testing, and Kover coverage. Follows TDD methodology with idiomatic Kotlin practices. Use when writing Kotlin tests with Kotest or MockK, or testing coroutines and checking coverage.

repo: affaan-m/ECC

인기도

GitHub 스타
280k
순위
#197
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬