@wuchen0993/claude-skill-unit-test
v1.0.2
Published
Java 单元测试编写技能,基于 JUnit 5 + Mockito + Spring Boot Test 框架
Downloads
275
Maintainers
Readme
Unit-Test Skill
Java 单元测试编写技能,基于 JUnit 5 + Mockito + Spring Boot Test 框架,帮助你快速编写规范、可靠的单元测试。
安装
通过 npm 安装(推荐)
# 全局安装
npm install -g @wuchen0993/claude-skill-unit-test
# 或者使用 npx(无需安装)
npx @wuchen0993/claude-skill-unit-test install安装后,技能会自动复制到 ~/.claude/skills/unit-test 目录(Windows: %USERPROFILE%\.claude\skills\unit-test)。
查看安装状态
npx @wuchen0993/claude-skill-unit-test status卸载
# 如果全局安装了
npm uninstall -g @wuchen0993/claude-skill-unit-test
# 删除技能文件
npx @wuchen0993/claude-skill-unit-test uninstall功能特性
- 智能测试策略选择 - 优先使用 Spring 上下文集成测试,当 Spring 无法启动时回退到 Mockito 纯单元测试
- 完整测试场景覆盖 - 正常成功、业务异常、参数异常、系统异常、边界条件
- 规范化代码生成 - 遵循 Given-When-Then 结构,统一命名规范
- 静态方法 Mock 支持 - 正确处理静态方法的 Mock 和资源释放
- MockMvc 集成 - 支持 Controller 层的 HTTP 接口测试
适用场景
- 为 Controller/Service 编写单元测试
- 修复失败的测试
- 提高测试覆盖率
- 参考现有测试模式编写新测试
使用方式
/unit-test或描述你的测试需求:
帮我为 UserController 编写单元测试测试策略
优先级 1: Spring 上下文集成测试(推荐)
当满足以下条件时优先使用:
- Spring 应用可以正常启动
- 需要测试 Bean 注入、AOP、配置加载
- 需要使用 MockMvc 测试 Controller
- 需要测试多个组件的协作
优点:
- 更接近真实运行环境
- 可以发现配置问题
- 测试 Bean 之间的依赖关系
优先级 2: Mockito 纯单元测试(备选)
当以下情况时使用:
- Spring 启动失败(外部依赖不可用)
- 需要隔离测试单个方法
- 快速反馈场景
- CI/CD 中需要快速执行
优点:
- 执行速度快
- 不依赖外部环境
- 可以精确控制测试条件
测试框架
| 框架 | 版本 | 用途 | |------|------|------| | JUnit Jupiter | 5.x | 测试框架 | | Mockito | 5.x | Mock 框架 | | Spring Boot Test | - | 集成测试 |
快速示例
Controller 集成测试(MockMvc)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class UserControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
@DisplayName("GET /api/users/{id} - 返回用户信息")
void getUser_shouldReturnUser_whenUserExists() throws Exception {
// Given
User user = new User(1L, "testuser");
when(userService.findById(1L)).thenReturn(user);
// When & Then
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1));
}
}Mockito 纯单元测试
@ExtendWith(MockitoExtension.class)
class UserControllerTest {
@Mock
private UserService userService;
@InjectMocks
private UserController controller;
@Test
@DisplayName("正常查询 - 返回用户信息")
void getUser_shouldReturnUser_whenUserExists() {
// Given
when(userService.getUserById(anyLong())).thenReturn(mockResponse);
// When
UserResponse response = controller.getUser(1L);
// Then
assertNotNull(response);
assertEquals(1L, response.getId());
}
}核心规范
测试方法命名
格式:methodName_shouldExpectedBehavior_whenCondition
// 推荐
void getUser_shouldReturnUser_whenUserExists()
void createUser_shouldReturn400_whenInvalidInput()
// 避免
void testGetUser()
void test1()Given-When-Then 结构
@Test
void example_givenWhenThen() {
// Given - 准备测试数据和 Mock 行为
UserRequest request = createUserRequest();
when(userService.createUser(any())).thenReturn(mockResponse);
// When - 执行被测方法
UserResponse actual = controller.createUser(request);
// Then - 验证结果
assertNotNull(actual);
verify(userService).createUser(any());
}测试场景覆盖
| 场景类型 | 示例 | |---------|------| | 正常成功 | 服务正常返回预期结果 | | 业务异常 | 业务规则校验失败、资源不存在 | | 参数异常 | IllegalArgumentException、InvalidParameterException | | 系统异常 | RuntimeException、NullPointerException | | 边界条件 | null 参数、空字符串、最大值、零值、负值 |
静态方法 Mock
private MockedStatic<SecurityContext> securityContextMock;
@BeforeEach
void setUp() {
securityContextMock = mockStatic(SecurityContext.class);
securityContextMock.when(SecurityContext::getCurrentUserId).thenReturn(TEST_USER_ID);
}
@AfterEach
void tearDown() {
securityContextMock.close(); // 必须关闭!
}参考文档
- patterns.md - 各类测试场景的详细模式
- test-example.md - Controller 测试完整示例
注意事项
1. HTTP POST 接口入参
如果没有特别声明,HTTP POST 接口一般都是 JSON 格式入参。即使 Controller 方法的入参是 ProtocolBuffer 类型,在测试类中使用 MockMvc 时也需要转成 JSON 字符串:
// ProtocolBuffer 转 JSON
String requestBody = JsonFormat.printer().print(req);
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isOk());2. Apollo 和 Dubbo 依赖
Apollo 和 Dubbo 相关依赖不会导致服务启动失败:
- Apollo 可以由使用者在运行测试类时补充启动参数解决
- 测试类所需的 yaml/yml 配置可以参考项目 resources 下的配置
- 大部分项目配置都已经依赖 Apollo
3. surefire 插件配置
如果需要传递 Apollo 或 JVM 启动参数,需要修改 surefire 插件配置:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
-Dapp.id=your-app-id
-Dapollo.meta=http://apollo-config-server
</argLine>
</configuration>
</plugin>运行测试
# 运行单个测试类
mvn test -Dtest=UserControllerTest
# 运行指定模块的测试
mvn test -Dtest=UserControllerTest -pl module-name
# 运行所有测试
mvn test
# 运行特定包下的测试
mvn test -Dtest="com.example.controller.*"