关于 testing-strategies
testing-strategies 是面向使用 Micronaut、Retrofit 和 MockK 项目的 Kotlin 测试参考。它说明端点与仓库测试覆盖、测试命名、协程模拟规则以及运行测试的命令。
主要功能
- 01端点集成测试指南
- 02仓库测试模式
- 03测试命名与覆盖要求
- 04MockK 和协程测试规则
- 05运行测试的 Gradle 命令
适用场景
- 01为 API 端点添加端到端测试
- 02检查认证失败和资源未找到行为
- 03测试仓库与协程代码
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ c0x12c/ ai-toolkit --skill testing-strategies安装后在 Claude Code 中输入/testing-strategies确认已加载。
附带文件examples.mdintegration-test-setup.md
详细介绍
测试策略 — 快速参考
有关 @MicronautTest 配置、Retrofit 客户端设置和连接池调优,请参阅
integration-test-setup.md。有关完整代码模式,包括 MockK、测试数据构建器和断言,请参阅
examples.md。
集成测试
每个端点都需要集成测试。继承 AbstractControllerTest,使用 module-client 中的 Retrofit 客户端,并在 @AfterEach 中通过 truncateAllTables() 清理数据。
关键规则:
- 始终使用 Retrofit 客户端 — 不要使用原始
HttpRequest - 通过
accessToken()生成真实的 JWT 令牌 - 端到端测试完整的 HTTP 堆栈,不要模拟管理器
测试命名
@Test
fun `{action} - {expected outcome}`() = runBlocking { }
// Examples:
fun `getEmployee - returns employee by id`() = runBlocking { }
fun `getEmployee - returns 404 when not found`() = runBlocking { }
fun `createEmployee - fails with 401 when not authenticated`() = runBlocking { }
每个端点的必需测试覆盖
- 正常路径 — 基本成功场景
- 未找到 — 缺少资源时返回 404
- 认证失败 — 不带令牌时返回 401
- 软删除 — 不返回已删除的记录
@Test
fun `getById - returns 404 when not found`() = runBlocking {
val token = accessToken(prepareUser())
assertThrows<HttpException> {
runBlocking {
client.getById(authorization = token, id = UUID.randomUUID())
}
}.also {
assertThat(it.code()).isEqualTo(404)
}
}
仓库测试
继承 AbstractRepositoryTest。每个仓库至少需要通过以下测试:
class DefaultEmployeeRepositoryTest : AbstractRepositoryTest() {
private val repository = DefaultEmployeeRepository(database)
@BeforeEach
fun cleanup() { database.primary.truncateAllTables() }
@Test
fun `insert - happy path`() { }
@Test
fun `byId - returns entity when exists`() { }
@Test
fun `byId - returns null when not exists`() { }
@Test
fun `byId - returns null when soft deleted`() { }
@Test
fun `deleteById - soft deletes entity`() { }
@Test
fun `update - updates selected fields`() { }
}
MockK 规则
- 使用
mockk<T>()创建模拟对象 - 对挂起函数使用
coEvery/coVerify(不要使用every/verify) - 使用
slot<T>()+capture()验证传入的参数 - 使用
kotlinx.coroutines.test中的runTest { }— 不要使用runBlocking。runTest会处理虚拟时间并捕获协程问题。 - 使用带注释的 AAA 模式:
// Given、// When、// Then - 使用
@Nested+@DisplayName对相关测试分组
有关完整的 MockK 代码示例、
@Nested模式、测试数据构建器和 AssertJ 断言,请参阅examples.md。
注意事项
连接池耗尽: 如果并行测试因 “cannot acquire connection” 失败,请将 maxPoolSize 提高到 20。配置片段请参阅 integration-test-setup.md。
MockK + 协程: 对挂起函数始终使用 coEvery / coVerify。普通的 every / verify 不起作用,还会产生令人困惑的错误。
运行测试
./gradlew test # All tests
./gradlew test --tests "com.yourcompany.EmployeeControllerTest" # One class
./gradlew :app:module-repository:test # One module
评论
支持 Markdown