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
- HMBSbige/skillstheir own version, first seen Oct 3, 2026
- vospr/context-engineering-templatetheir own version, first seen Oct 1, 2026
- Cure-Consulting-Group/ProductEngineeringSkillstheir own version, first seen Sep 28, 2026
- komluk/scaffoldingtheir own version, first seen Sep 28, 2026
- Ygohel18/skillstheir own version, first seen Sep 27, 2026
- BGLuis/skillstheir own version, first seen Sep 15, 2026
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.
benshapyroSkillreact-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
MicrosoftSkillapi-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
OpenAISkillobservability
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 AzureSkillgit-workflow
Squad branching model: dev-first workflow with insiders preview channel
Also in 6 projects that use this
MicrosoftSkillerror-handling
统一错误处理系统。在添加 API 端点、修改错误处理、添加前端 API 调用、编写错误相关测试时使用。
Also in 3 projects that use this
CloudAI-XSkilldatabase-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
Other versions37 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 37
- anthropics/knowledge-work-plugins★ 26ksame name
- irahardianto/awesome-agv★ 157same name
- AnastasiyaW/codex-claude-code-config★ 153same name
- zakariaf/Flutter-Skills★ 52same name
- shinpr/agentic-code★ 49same name
- addxai/enterprise-harness-engineering★ 44same name
- drafthq/draft★ 40same name
- Hack23/European-Parliament-MCP-Server★ 28same name
- suhailkakar/the-skills★ 26same name
- komluk/scaffolding★ 15same name
27 more not listed
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository193 other files it gives its agents.
- .agents/AGENTS.mdAGENTS.md
- AGENTS.mdAGENTS.md
- .claude/CLAUDE.mdCLAUDE.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/behavioral-discipline.mdcCursor rule
- .cursor/rules/context-budget.mdcCursor rule
- .cursor/rules/orchestration.mdcCursor rule
- .cursor/rules/yagni-stdlib.mdcCursor rule
- androidSkill
- android-ui-designSkill
- api-versioningSkill
- astroSkill
- auth-token-inspectorSkill
- backlogSkill
- cc-api-contractSkill
- cc-db-migrationSkill
- cc-featureSkill
- cc-fixSkill
- cc-pagespeedSkill
- cc-refactorSkill
- cc-reviewSkill
- cc-spec-mutationSkill
- cc-tdd-cycleSkill
- cc-test-planSkill
- code-reviewSkill
- commitSkill
- conductor-setupSkill
- councilSkill
- django-ormSkill
- django-testingSkill
- django-uvSkill
- drizzle-schema-architectSkill
- evaluationSkill
- fastapi-pydantic-strictSkill
- find-skillsSkill
- jpa-nplusone-detectorSkill
- jpa-postgresSkill
- laravel-specialistSkill
- livewire-alpine-bridgeSkill
- multi-agent-orchestrationSkill
- nextjs-typescriptSkill
- openspecSkill
- pagespeed-insightsSkill
- pagespeed-perfSkill
- php-proSkill
- python-django-stackSkill
- python-fastapi-stackSkill
- pythonSkill
- security-ai-llmSkill
- security-blue-teamSkill
- security-cloudSkill
- security-cryptoSkill
- security-exploit-devSkill
- security-grcSkill
- security-incident-responseSkill
- security-log-analysisSkill
- security-malware-analysisSkill
- security-mobileSkill
- security-networkSkill
- security-ot-icsSkill
- The first 60 shown.
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
- Distinctive: line 63
If you find yourself writing more integration tests than unit tests, the code under test has too many responsibilities bundled together.
- Distinctive: line 112
Every test follows Arrange → Act → Assert.
- Distinctive: line 134
No inline comments between phases once the structure is clear.
- Very specific: line 142
JPA mapping: Do not test that @Column(name = "email") maps to the right column.
- Very specific: line 234
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 …
- Very specific: line 316
Use RANDOM_PORT only when you need real HTTP (e.g., testing HTTP client behavior, WebSockets, or SSE).
- Distinctive: line 380
Never hardcode UUIDs or share mutable state between tests.
- Very specific: line 419
Default values use UUID.randomUUID() to ensure tests do not share state through hardcoded IDs or emails.
- Distinctive: line 424
New behavior: Every new feature requires at minimum one unit test and one integration test covering the happy path.
- Distinctive: line 428
Bug fix: Write a regression test that reproduces the bug before fixing it.
- Distinctive: line 443
Refactor: Do not write new tests. The existing tests must pass unchanged.
- Distinctive: line 483
Do not mix unit and integration test tags in the same class.
“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.
Files
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:
- Unit tests (fastest — fail fast)
- Integration tests with H2 (
@DataJpaTest) - 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.
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
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.

