npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@wuchen0993/claude-skill-unit-test

v1.0.2

Published

Java 单元测试编写技能,基于 JUnit 5 + Mockito + Spring Boot Test 框架

Downloads

275

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();  // 必须关闭!
}

参考文档

注意事项

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.*"