unit-testing

15
0
Source

单元测试编写指南,涵盖 JUnit5/MockK 使用、测试命名规范、Mock 技巧、测试覆盖率要求、TDD 实践。当用户编写单元测试、Mock 依赖、提高测试覆盖率或进行测试驱动开发时使用。

Install

mkdir -p .claude/skills/unit-testing && curl -L -o skill.zip "https://mcp.directory/api/skills/download/1686" && unzip -o skill.zip -d .claude/skills/unit-testing && rm skill.zip

Installs to .claude/skills/unit-testing

About this skill

单元测试编写

Quick Reference

框架:JUnit 5 (Jupiter) + MockK 1.12.2
测试基类:BkCiAbstractTest(提供 dslContext、objectMapper)
文件命名:*Test.kt
测试模式:AAA(Arrange-Act-Assert)

最简示例

class PipelineServiceTest : BkCiAbstractTest() {
    private val pipelineDao = mockk<PipelineDao>()
    private val service = PipelineService(pipelineDao)

    @Test
    fun `should return pipeline when exists`() {
        // Arrange
        every { pipelineDao.get(any(), any()) } returns mockPipeline
        
        // Act
        val result = service.getPipeline(PROJECT_ID, PIPELINE_ID)
        
        // Assert
        Assertions.assertNotNull(result)
        verify { pipelineDao.get(PROJECT_ID, PIPELINE_ID) }
    }
    
    companion object {
        const val PROJECT_ID = "test-project"
        const val PIPELINE_ID = "p-12345678901234567890123456789012"
    }
}

When to Use

  • 编写 Service/DAO 层单元测试
  • Mock 外部依赖
  • 验证业务逻辑正确性
  • 进行 TDD 开发

When NOT to Use

  • 集成测试 → 需要启动完整服务
  • E2E 测试 → 需要部署完整环境

测试基类

abstract class BkCiAbstractTest {
    protected val dslContext: DSLContext = DSL.using(
        MockConnection(Mock.of(0)),
        SQLDialect.MYSQL
    )
    protected val objectMapper: ObjectMapper = JsonUtil.getObjectMapper()
}

Mock 创建方式

// 基础 Mock
private val dao = mockk<PipelineDao>()

// Relaxed Mock(自动返回默认值)
private val service = mockk<PipelineService>(relaxed = true)

// Spy(部分 Mock)
private val self = spyk(MyService(), recordPrivateCalls = true)

// Spring Bean Mock
mockkObject(SpringContextUtil)
every { SpringContextUtil.getBean(CommonConfig::class.java) } returns config

Stub 行为定义

// 简单返回
every { dao.get(any(), any()) } returns mockData

// 条件应答
every { redis.execute(any<RedisScript<*>>(), any(), any()) } answers {
    val script = args[0] as DefaultRedisScript<*>
    if (script.resultType == Long::class.java) 1L else throw RuntimeException()
}

// 抛出异常
every { service.doSomething() } throws ErrorCodeException(...)

断言与验证

// 基本断言
Assertions.assertEquals(expected, actual)
Assertions.assertTrue(condition)
Assertions.assertNull(value)

// 异常断言
val ex = assertThrows<ErrorCodeException> { service.doSomething() }
Assertions.assertEquals("2100013", ex.errorCode)

// 验证调用
verify { dao.get(any(), any()) }
verify(exactly = 1) { service.save(any()) }
verify(exactly = 0) { service.delete(any()) }

测试组织

class MyServiceTest {
    @Nested
    inner class GetPipelineTests {
        @Test
        @DisplayName("流水线存在时返回数据")
        fun `returns pipeline when exists`() { }
        
        @Test
        @DisplayName("流水线不存在时抛出异常")
        fun `throws exception when not found`() { }
    }
}

测试数据构建

// Builder 模式
fun buildOptions(
    enable: Boolean = true,
    runCondition: RunCondition = RunCondition.PRE_TASK_SUCCESS
) = ElementAdditionalOptions(enable = enable, runCondition = runCondition)

// 从资源文件加载
val resource = ClassPathResource("test-data/pipeline.json")
val data = JsonUtil.to(resource.inputStream, PipelineInfo::class.java)

Checklist

编写测试前确认:

  • 继承 BkCiAbstractTest 基类
  • 使用 AAA 模式组织测试代码
  • Mock 所有外部依赖
  • 覆盖正常和异常场景
  • 测试方法名清晰描述测试意图

More by TencentBlueKing

View all →

store-module-architecture

TencentBlueKing

Store 研发商店模块架构指南,涵盖插件/模板/镜像管理、版本发布、审核流程、商店市场、扩展点机制。当用户开发研发商店功能、发布插件、管理模板或实现扩展点时使用。

00

00-bkci-global-architecture

TencentBlueKing

BK-CI 全局架构指南,以流水线为核心的模块协作全景图,涵盖完整执行流程、模块依赖关系、数据流向、核心概念。当用户需要理解系统架构、进行跨模块开发、了解模块间协作或规划架构设计时优先阅读。

10

auth-module-architecture

TencentBlueKing

Auth 权限认证模块架构指南,涵盖 IAM 集成、RBAC 权限模型、资源权限校验、权限迁移、OAuth 认证。当用户开发权限功能、配置 IAM 资源、实现权限校验或处理认证流程时使用。

10

go-agent-development

TencentBlueKing

Go Agent 开发指南,涵盖 Agent 架构设计、心跳机制、任务执行、日志上报、升级流程、与 Dispatch 模块交互。当用户开发构建机 Agent、实现任务执行逻辑、处理 Agent 通信或进行 Go 语言开发时使用。

00

supporting-modules-architecture

TencentBlueKing

BK-CI 支撑模块架构指南,涵盖凭证管理(Ticket)、构建机环境(Environment)、通知服务(Notify)、构建日志(Log)、质量红线(Quality)、开放接口(OpenAPI)等支撑性服务模块。当用户开发这些模块功能或需要理解支撑服务架构时使用。

100

yaml-pipeline-transfer

TencentBlueKing

YAML 流水线转换指南,涵盖 YAML 与 Model 双向转换、PAC(Pipeline as Code)实现、模板引用、触发器配置。当用户需要解析 YAML 流水线、实现 PAC 模式、处理流水线模板或进行 YAML 语法校验时使用。

20

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

237773

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

181404

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

163268

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

194225

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

154189

rust-coding-skill

UtakataKyosui

Guides Claude in writing idiomatic, efficient, well-structured Rust code using proper data modeling, traits, impl organization, macros, and build-speed best practices.

153171

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.