agentleFS
lgzarturolgzarturo/codeconductor/skills/testing-strategy/SKILL.md

testing-strategy

Skill0 starsChanged 2 months agoMITView on GitHub

Provides expert knowledge of the testing pyramid, test design principles, MockK patterns, and integration testing conventions for Spring Boot + Kotlin projects.

37 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use react-patterns, api-design and 10 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • benshapyroSkill

    react-patterns

    Modern React patterns for TypeScript applications including hooks, state management, and component composition. Use when building React components, managing state, or implementing React best practices.

    Also in 4 projects that use this

  • MicrosoftSkill

    api-design

    Guide for designing and documenting RESTful APIs. Use when asked to design an API, create endpoints, or document an API.

    Also in 10 projects that use this

  • OpenAISkill

    observability

    Vercel Observability expert guidance — Drains (logs, traces, speed insights, web analytics), Web Analytics, Speed Insights, runtime logs, custom events, OpenTelemetry integration, and monitoring dashboards. Use when instrumenting, debugging, or optimizing application performance and user experience on Vercel.

    Also in 5 projects that use this

  • Microsoft AzureSkill

    git-workflow

    Squad branching model: dev-first workflow with insiders preview channel

    Also in 6 projects that use this

  • MicrosoftSkill

    error-handling

    统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用。

    Also in 3 projects that use this

  • CloudAI-XSkill

    database-design

    Designs database schemas, indexing strategies, query optimization, and migration patterns for SQL and NoSQL databases. Use when designing tables, optimizing queries, fixing N+1 problems, planning migrations, or when asked about database performance, normalization, ORMs, or data modeling.

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

12 rules. 0 are common, 8 are distinctive, and 4 are very specific to this project.

  • 0

    Common

    Most of the 33 edited versions we read keep these.

  • 8

    Distinctive

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    If you find yourself writing more integration tests than unit tests, the code under test has too many responsibilities bundled together.

    line 63
  2. Distinctive:

    Every test follows Arrange → Act → Assert.

    line 112
  3. Distinctive:

    No inline comments between phases once the structure is clear.

    line 134
  4. Very specific:

    JPA mapping: Do not test that @Column(name = "email") maps to the right column.

    line 142
  5. Very specific:

    Do not use relaxed = true on mocks where you need to verify behavior — a relaxed mock does not fail on unexpected calls, which can hide …

    line 234
  6. Very specific:

    Use RANDOM_PORT only when you need real HTTP (e.g., testing HTTP client behavior, WebSockets, or SSE).

    line 316
  7. Distinctive:

    Never hardcode UUIDs or share mutable state between tests.

    line 380
  8. Very specific:

    Default values use UUID.randomUUID() to ensure tests do not share state through hardcoded IDs or emails.

    line 419
  9. Distinctive:

    New behavior: Every new feature requires at minimum one unit test and one integration test covering the happy path.

    line 424
  10. Distinctive:

    Bug fix: Write a regression test that reproduces the bug before fixing it.

    line 428
  11. Distinctive:

    Refactor: Do not write new tests. The existing tests must pass unchanged.

    line 443
  12. Distinctive:

    Do not mix unit and integration test tags in the same class.

    line 483

“Common” is measured: kept by at least 6 in 10 of the 33 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Testing Strategy

Testing Pyramid

       /\
      /  \
     / E2E\       10% — full API, happy path + main error cases
    /------\
   /  Integ \     20% — components with real dependencies (DB, HTTP)
  /----------\
 /    Unit    \   70% — isolated, mocked dependencies, fast
/______________\

Unit tests are the foundation. They are fast, deterministic, and cheap to run. Integration tests validate that components work together. E2E tests validate that the system works end to end — keep them minimal.

If you find yourself writing more integration tests than unit tests, the code under test has too many responsibilities bundled together.

Test Naming Convention

Format: should [expected behavior] when [condition]

@Test
fun `should return user when found by id`() { ... }

@Test
fun `should return 404 when user does not exist`() { ... }

@Test
fun `should throw ConflictException when email already exists`() { ... }

@Test
fun `should not return deleted users in list`() { ... }

Group related tests with @Nested:

@ExtendWith(MockKExtension::class)
class UserServiceTest {

    @Nested
    inner class GetById {
        @Test
        fun `should return user when found`() { ... }

        @Test
        fun `should return NotFound when user does not exist`() { ... }
    }

    @Nested
    inner class Create {
        @Test
        fun `should create and return user when email is unique`() { ... }

        @Test
        fun `should throw ConflictException when email already exists`() { ... }
    }
}

Unit Test Structure (AAA)

Every test follows Arrange → Act → Assert. Use blank lines to separate each phase.

@Test
fun `should return user when found by id`() {
    // Arrange
    val userId = UUID.randomUUID()
    val user = User(id = userId, email = "user@example.com", name = "Test User")
    every { userRepository.findById(userId) } returns Optional.of(user)

    // Act
    val result = userService.getById(userId)

    // Assert
    assertThat(result).isInstanceOf(UserResult.Found::class.java)
    val found = result as UserResult.Found
    assertThat(found.user.id).isEqualTo(userId)
    verify(exactly = 1) { userRepository.findById(userId) }
}

No inline comments between phases once the structure is clear. The blank lines are enough.

What NOT to Test

Framework wiring. Spring handles dependency injection. Do not write tests that verify @Autowired works.

JPA mapping. Do not test that @Column(name = "email") maps to the right column. That is Hibernate's job.

Trivial getters and setters. A data class property has no logic. There is nothing to test.

Private methods directly. Private methods are implementation details. Test them through the public behavior that uses them. If a private method is complex enough to need its own test, it should be extracted into a separate class.

Implementation, not behavior. Tests that verify HOW something is done (mock call order, internal state) are brittle. Test WHAT the output or side effect is.

// bad — tests implementation detail
verify { userRepository.findById(any()) }
verify { cacheService.put(any(), any()) }
verify(ordering = Ordering.ORDERED) {   // this is too coupled to internals
    userRepository.findById(userId)
    cacheService.put(userId, user)
}

// good — tests observable behavior
assertThat(result).isEqualTo(expectedUser)

MockK Patterns

Basic Setup

@ExtendWith(MockKExtension::class)
class UserServiceTest {

    @MockK
    private lateinit var userRepository: UserRepository

    @MockK
    private lateinit var emailService: EmailService

    private lateinit var userService: UserService

    @BeforeEach
    fun setUp() {
        userService = UserService(userRepository, emailService)
    }
}

Stubbing

// Return value
every { userRepository.findById(userId) } returns Optional.of(user)

// Return null (for nullable return types)
every { userRepository.findByEmail(any()) } returns null

// Throw exception
every { userRepository.save(any()) } throws DataIntegrityViolationException("Duplicate")

// Return different values on successive calls
every { userRepository.findById(any()) } returnsMany listOf(Optional.of(user), Optional.empty())

// Answer with computation
every { userRepository.save(any()) } answers { firstArg() }

Verification

// Verify called exactly once with specific argument
verify(exactly = 1) { userRepository.findById(userId) }

// Verify called with any argument
verify { emailService.sendWelcome(any()) }

// Verify never called
verify(exactly = 0) { emailService.sendWelcome(any()) }

// Verify called with specific argument
verify { emailService.sendWelcome(match { it.email == "user@example.com" }) }

Relaxed Mocks

// relaxed = true — returns default values (null, 0, false, empty list)
// Use only when you do not care about the return value of any method
val logger = mockk<Logger>(relaxed = true)

Do not use relaxed = true on mocks where you need to verify behavior — a relaxed mock does not fail on unexpected calls, which can hide bugs.

Coroutines

// Stubbing suspend functions
coEvery { userRepository.findById(userId) } returns user

// Verifying suspend functions
coVerify(exactly = 1) { userRepository.findById(userId) }

Argument Matchers

// Any value
every { service.process(any()) } returns result

// Specific type
every { service.process(any<UserRequest>()) } returns result

// Custom predicate
every { service.notify(match { it.email.endsWith("@example.com") }) } just Runs

// Capture for assertion
val slot = slot<User>()
every { userRepository.save(capture(slot)) } returns savedUser
// ... trigger the action ...
assertThat(slot.captured.email).isEqualTo("expected@example.com")

Integration Test Patterns

Controller Tests with MockMvc

@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {

    @Autowired
    private lateinit var mockMvc: MockMvc

    @Autowired
    private lateinit var objectMapper: ObjectMapper

    @Test
    fun `should return 200 with user when found`() {
        mockMvc.perform(
            get("/api/v1/users/${existingUser.id}")
                .contentType(MediaType.APPLICATION_JSON)
        )
            .andExpect(status().isOk)
            .andExpect(jsonPath("$.email").value(existingUser.email))
            .andExpect(jsonPath("$.id").value(existingUser.id.toString()))
    }

    @Test
    fun `should return 400 when request body is invalid`() {
        val invalidRequest = mapOf("email" to "not-an-email")

        mockMvc.perform(
            post("/api/v1/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(invalidRequest))
        )
            .andExpect(status().isBadRequest)
            .andExpect(jsonPath("$.code").value("VALIDATION_ERROR"))
    }

    @Test
    fun `should return 404 when user is not found`() {
        mockMvc.perform(get("/api/v1/users/${UUID.randomUUID()}"))
            .andExpect(status().isNotFound)
    }
}

@AutoConfigureMockMvc configures MockMvc without starting a real HTTP server. The test is faster than RANDOM_PORT but still tests the full Spring MVC stack.

Use RANDOM_PORT only when you need real HTTP (e.g., testing HTTP client behavior, WebSockets, or SSE).

Database Tests with Testcontainers

@SpringBootTest
@Testcontainers
class UserRepositoryIntegrationTest {

    companion object {
        @Container
        @JvmStatic
        val postgres = PostgreSQLContainer<Nothing>("postgres:16").apply {
            withDatabaseName("testdb")
            withUsername("test")
            withPassword("test")
        }

        @DynamicPropertySource
        @JvmStatic
        fun overrideProperties(registry: DynamicPropertyRegistry) {
            registry.add("spring.datasource.url", postgres::getJdbcUrl)
            registry.add("spring.datasource.username", postgres::getUsername)
            registry.add("spring.datasource.password", postgres::getPassword)
        }
    }

    @Autowired
    private lateinit var userRepository: UserRepository

    @Test
    fun `should enforce unique email at database level`() {
        userRepository.save(User(email = "unique@example.com", name = "First"))
        assertThrows<DataIntegrityViolationException> {
            userRepository.save(User(email = "unique@example.com", name = "Second"))
        }
    }
}

Share the container across test classes using a base class with @Container on a static field. Testcontainers reuses the same container if the configuration is identical.

Seed Data with @Sql

@SpringBootTest
@AutoConfigureMockMvc
@Sql("/test-data/users.sql")   // runs before each test in this class
class UserControllerTest { ... }

// Or per-test
@Test
@Sql("/test-data/users-with-orders.sql")
fun `should return orders when user has orders`() { ... }

SQL files go in src/test/resources/test-data/. Use descriptive names that explain what state they create, not what feature they serve.

Test Data Factories

Never hardcode UUIDs or share mutable state between tests.

object UserTestFactory {

    fun create(
        id: UUID = UUID.randomUUID(),
        email: String = "user-${UUID.randomUUID()}@example.com",
        name: String = "Test User",
        role: UserRole = UserRole.USER
    ): User = User(
        id = id,
        email = email,
        name = name,
        role = role
    )

    fun createRequest(
        email: String = "user-${UUID.randomUUID()}@example.com",
        name: String = "Test User"
    ): CreateUserRequest = CreateUserRequest(
        email = email,
        name = name
    )

    fun createAdmin(): User = create(role = UserRole.ADMIN)

    fun createList(count: Int): List<User> = (1..count).map { create() }
}

Usage in tests:

val user = UserTestFactory.create(email = "specific@example.com")
val admin = UserTestFactory.createAdmin()
val users = UserTestFactory.createList(5)

Default values use UUID.randomUUID() to ensure tests do not share state through hardcoded IDs or emails.

When Tests Are Required

New behavior. Every new feature requires at minimum one unit test and one integration test covering the happy path. Edge cases and error paths require additional unit tests.

Bug fix. Write a regression test that reproduces the bug before fixing it. The test must fail before the fix and pass after. This prevents the bug from reappearing silently.

// Example: bug where findByEmail returned deleted users
@Test
fun `should not return deleted user — regression for bug #42`() {
    val user = userRepository.save(UserTestFactory.create(email = "gone@example.com"))
    userRepository.delete(user)
    val result = userRepository.findByEmail("gone@example.com")
    assertThat(result).isNull()
}

Refactor. Do not write new tests. The existing tests must pass unchanged. If they do not, the refactor changed behavior — that is a bug.

High-risk paths. Security, payment processing, data migrations, and permission checks require contract tests in addition to unit and integration tests. These paths have severe consequences if broken.

CI Integration

Tests must run in CI on every pull request. The pipeline must fail if any test fails.

Recommended test execution order:

  1. Unit tests (fastest — fail fast)
  2. Integration tests with H2 (@DataJpaTest)
  3. Integration tests with Testcontainers (slowest — run last)

Separate test tasks in Gradle:

// build.gradle.kts
tasks.register<Test>("integrationTest") {
    description = "Runs integration tests"
    group = "verification"
    useJUnitPlatform {
        includeTags("integration")
    }
    shouldRunAfter(tasks.test)
}

Tag integration tests:

@Tag("integration")
@SpringBootTest
class UserRepositoryIntegrationTest { ... }

Do not mix unit and integration test tags in the same class. A test class is either one or the other.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.