
junit-mockito-patterns
JUnit5 + Mockito 测试框架技能。覆盖 JUnit5 @ExtendWith替代@RunWith、Mockito @Mock/@InjectMocks规则、测试隔离原则(FIRST)、@SpringBootTest何时用何时不用(@WebMvcTest/@DataJpaTest切片测试)、BDDMockito given/willReturn风格、ArgumentCaptor参数捕获、verify行为验证、@ParameterizedTest参数化测试。 当用户编写 Java 单元测试/集成测试、Mock外部依赖时需要此技能。
- Installs
- 100
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/full-stack-skills/java-skills --skill junit-mockito-patterns- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads junit-mockito-patterns automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
JUnit5 + Mockito 测试规则
来源:https://junit.org/junit5/docs/current/user-guide/
Mockito:https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html
Capability Boundaries
✅ Strong Suits
- JUnit5 迁移规则 — @ExtendWith 替代 @RunWith, @Test 导入 org.junit.jupiter.api
- Mockito 规则 — @Mock(外部依赖) + @InjectMocks(被测试对象), 不 Mock POJO
- 测试隔离(FIRST原则) — Fast/Independent/Repeatable/Self-Validating/Timely
- 切片测试 — @WebMvcTest(Controller) / @DataJpaTest(Repository) / @JsonTest
- BDD风格 — BDDMockito.given()/willReturn()/then().should() 替代 when/thenReturn/verify
- 行为验证 — verify() + ArgumentCaptor
- @ParameterizedTest + @MethodSource — 参数化测试简化多场景
- @Nested 分组 — 组织相关测试场景
❌ Out of Scope
- 集成测试/端到端测试 → Playwright/Selenium(已有技能)
- 性能测试 → JMH(Java Microbenchmark Harness)
JUnit4 → JUnit5 迁移对照
| JUnit4 | JUnit5 | 说明 |
|---|---|---|
@RunWith(SpringRunner.class) | @ExtendWith(SpringExtension.class) | 扩展机制 |
@RunWith(MockitoJUnitRunner.class) | @ExtendWith(MockitoExtension.class) | Mockito扩展 |
@Test(expected = Exception.class) | assertThrows(Exception.class, () -> {...}) | 异常断言 |
@Before | @BeforeEach | 每个测试前执行 |
@After | @AfterEach | 每个测试后执行 |
@BeforeClass | @BeforeAll | 所有测试前(static) |
@AfterClass | @AfterAll | 所有测试后(static) |
@Ignore | @Disabled | 禁用测试 |
@FixMethodOrder | @TestMethodOrder(MethodName) | 测试顺序 |
LLM最常犯的错误
| # | 错误 | 正确做法 |
|---|---|---|
| 1 | import org.junit.Test (JUnit4) | import org.junit.jupiter.api.Test (JUnit5) |
| 2 | @RunWith(MockitoJUnitRunner.class) | @ExtendWith(MockitoExtension.class) |
| 3 | 测试 Service 用 @SpringBootTest 启动整个上下文 | 用 @ExtendWith(MockitoExtension.class) 纯 Mockito |
| 4 | Controller 测试启动整个应用 | @WebMvcTest + @MockBean 只加载 Controller 层 |
| 5 | Mock 值对象(POJO/DTO) | 只 Mock 外部依赖(DB/HTTP/MQ),POJO 直接 new |
| 6 | verify(mock, never()) 不写 times(0) | verify(mock, never()).method() 或 verify(mock, times(0)).method() |
| 7 | 每个测试方法都 initMocks(this) | @ExtendWith 自动初始化 |
| 8 | 用 when().thenReturn() (非BDD) | BDD 风格: given().willReturn() |
| 9 | @SpringBootTest 做单元测试(慢,3s+) | 切片测试 < 200ms |
| 10 | 不写 @DisplayName | 测试方法中文描述,方便定位 |
核心规则速查
纯单元测试(推荐)
@ExtendWith(MockitoExtension.class)
@DisplayName("用户服务测试")
class UserServiceTest {
@Mock UserRepository userRepo; // 外部依赖
@Mock CacheManager cacheManager;
@InjectMocks UserService userService; // 被测试对象(构造器注入)
@Test
@DisplayName("查询用户-缓存命中-直接返回")
void getUser_CacheHit_ReturnFromCache() {
// given(BDD风格)
User cached = new User(1L, "zhang");
given(cacheManager.get("user:1")).willReturn(cached);
// when
User result = userService.getUser(1L);
// then
assertThat(result.getName()).isEqualTo("zhang");
then(userRepo).should(never()).findById(anyLong()); // BDD验证
}
@Test
@DisplayName("查询用户-未命中-查DB并缓存")
void getUser_CacheMiss_QueryDBAndCache() {
// given
given(cacheManager.get("user:1")).willReturn(null);
given(userRepo.findById(1L)).willReturn(Optional.of(new User(1L, "zhang")));
// when
User result = userService.getUser(1L);
// then
assertThat(result).isNotNull();
then(cacheManager).should().set(eq("user:1"), any(User.class));
}
}
Controller 切片测试
@WebMvcTest(UserController.class)
@DisplayName("用户控制器测试")
class UserControllerTest {
@Autowired MockMvc mockMvc;
@MockBean UserService userService;
@Test
@DisplayName("GET /user/1 返回用户信息")
void getUser_ById_ReturnsUser() throws Exception {
given(userService.getUser(1L)).willReturn(new UserVO(1L, "zhang"));
mockMvc.perform(get("/user/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("zhang"));
}
@Test
@DisplayName("GET /user/1 用户不存在返回404")
void getUser_NotFound_Returns404() throws Exception {
given(userService.getUser(99L)).willThrow(new UserNotFoundException(99L));
mockMvc.perform(get("/user/99"))
.andExpect(status().isNotFound());
}
}
Repository 切片测试
@DataJpaTest
@DisplayName("用户仓库测试")
class UserRepositoryTest {
@Autowired TestEntityManager em;
@Autowired UserRepository repo;
@Test
@DisplayName("按用户名查询-存在-返回用户")
void findByUsername_Exists_ReturnUser() {
em.persistAndFlush(new User("zhang", "zhang@test.com"));
Optional<User> result = repo.findByUsername("zhang");
assertThat(result).isPresent();
assertThat(result.get().getEmail()).isEqualTo("zhang@test.com");
}
@Test
@DisplayName("按用户名查询-不存在-返回空")
void findByUsername_NotExists_ReturnEmpty() {
Optional<User> result = repo.findByUsername("nonexistent");
assertThat(result).isEmpty();
}
}
参数化测试
@ExtendWith(MockitoExtension.class)
class PriceServiceTest {
@InjectMocks PriceService priceService;
@ParameterizedTest
@MethodSource("discountParams")
@DisplayName("计算折扣-多场景验证")
void calcDiscount_Scenarios(BigDecimal price, int level, BigDecimal expected) {
assertThat(priceService.calcDiscount(price, level))
.isEqualByComparingTo(expected);
}
static Stream<Arguments> discountParams() {
return Stream.of(
Arguments.of(new BigDecimal("100"), 1, new BigDecimal("100")),
Arguments.of(new BigDecimal("100"), 2, new BigDecimal("90")), // 9折
Arguments.of(new BigDecimal("100"), 3, new BigDecimal("80")) // 8折
);
}
}
ArgumentCaptor 参数捕获
@Test
@DisplayName("注册用户-验证发送欢迎邮件")
void registerUser_ShouldSendWelcomeEmail() {
@Captor ArgumentCaptor<EmailMessage> emailCaptor;
given(mailClient.send(any())).willReturn(true);
userService.register("test@test.com", "张三");
then(mailClient).should().send(emailCaptor.capture());
EmailMessage msg = emailCaptor.getValue();
assertThat(msg.getTo()).isEqualTo("test@test.com");
assertThat(msg.getSubject()).contains("欢迎");
}
@Nested 组织测试
@ExtendWith(MockitoExtension.class)
@DisplayName("订单服务测试")
class OrderServiceTest {
@Mock OrderRepository orderRepo;
@InjectMocks OrderService orderService;
@Nested
@DisplayName("创建订单")
class CreateOrder {
@Test
@DisplayName("正常创建-返回订单ID")
void normal_ReturnOrderId() { ... }
@Test
@DisplayName("库存不足-抛异常")
void noStock_ThrowException() { ... }
}
@Nested
@DisplayName("取消订单")
class CancelOrder {
@Test
@DisplayName("已支付-退款并取消")
void paid_RefundAndCancel() { ... }
@Test
@DisplayName("已取消-幂等")
void alreadyCancelled_Idempotent() { ... }
}
}
测试选择决策树
需要测试什么?
├── Service/业务逻辑
│ ├── 纯逻辑(无外部依赖) → @Test + new 对象
│ └── 有DB/HTTP/MQ依赖 → @ExtendWith(MockitoExtension.class) + @Mock/@InjectMocks
├── Controller/API
│ └── @WebMvcTest + @MockBean
├── Repository/数据层
│ └── @DataJpaTest + TestEntityManager
├── JSON序列化
│ └── @JsonTest
└── 集成测试(多组件)
└── @SpringBootTest(慎用,仅关键流程)
Gotchas
- @Mock 不 Mock POJO — 只 Mock 外部依赖,POJO 直接 new
- @SpringBootTest 启动整个上下文(慢) — 优先用切片测试 @WebMvcTest/@DataJpaTest
- AssertJ 断言优于 assertEquals —
assertThat(x).isEqualTo(y)更可读、链式调用 - @MockBean 和 @Mock 不同 — @MockBean 是 Spring 容器中的 Mock(集成测试),@Mock 是纯 Mockito(单元测试)
- verify() 验证次数默认 times(1) — 调用0次需显式用
never()或times(0) - @MockitoExtension 自动初始化 mocks — 不需要在 @BeforeEach 调用 MockitoAnnotations.openMocks(this)
- 测试方法命名 —
methodName_StateUnderTest_ExpectedBehavior或@DisplayName中文描述 - JUnit5 @Nested 组织相关测试 — 替代 JUnit4 的 @FixMethodOrder
- @InjectMocks 必须是具体类 — 不能是接口或抽象类(需要实例化)
- Mockito 不能 Mock 构造方法、final 类、静态方法(默认) — 需要 PowerMock/Mockito Inline
- BDDMockito.then(mock).should() 替代 verify(mock) — 更符合 Given-When-Then 结构
- @Captor 比手动创建 ArgumentCaptor 更简洁 — 声明式参数捕获
Data Privacy
本技能不收集、存储或传输任何用户数据。
FAQ
What does the junit-mockito-patterns skill do?
JUnit5 + Mockito 测试框架技能。覆盖 JUnit5 @ExtendWith替代@RunWith、Mockito @Mock/@InjectMocks规则、测试隔离原则(FIRST)、@SpringBootTest何时用何时不用(@WebMvcTest/@DataJpaTest切片测试)、BDDMockito given/willReturn风格、ArgumentCaptor参数捕获、verify行为验证、@ParameterizedTest参数化测试。 当用户编写 Java 单元测试/集成测试、Mock外部依赖时需要此技能。
How do I install junit-mockito-patterns?
Run npx skills add https://github.com/full-stack-skills/java-skills --skill junit-mockito-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/junit-mockito-patterns/ (personal) or .claude/skills/junit-mockito-patterns/ (project).
Which AI agents can use junit-mockito-patterns?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is junit-mockito-patterns safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains junit-mockito-patterns?
It is published by full-stack-skills in full-stack-skills/java-skills. It has 100 recorded installs.
More from full-stack-skills/java-skills
java-development-manual
full-stack-skills/java-skills
Java开发手册规约集合,基于阿里巴巴Java开发手册(嵩山版)。 涵盖7大维度:编程规约、异常日志、单元测试、安全规约、MySQL数据库、工程结构、设计规约。 当用户需要:(1) 编写或审查Java代码 (2) 检查命名/代码规范 (3) 处理异常和日志 (4) 编写单元测试 (5) 安全编码 (6) 数据库设计 (7) 工程架构设计时使用此skill。 触发词:Java规范、阿里规约、代码规范、开发手册、编程规约、异常处理、单元测试、安全、MySQL、工程结构、设计模式。
mybatis-plus-patterns
full-stack-skills/java-skills
Open the skill to read its SKILL.md instructions.
java-code-comments
full-stack-skills/java-skills
Provides comprehensive guidance for adding Java code comments following industry standards and best practices. This skill helps add class-level comments, method-level comments, and field-level comments to Java code. Use when the user wants to add comments to Java code, needs to document Java classes/methods/fields, wants to improve code documentation, or needs to generate JavaDoc comments. This skill covers Controller, Service, ServiceImpl, Mapper, Model, Entity, BO (Business Object), DTO, VO, and other common Java component types. The skill follows a systematic workflow: scan codebase, identify components, create todo list, and add comments in order (class comments → method comments → field comments).
mybatis-patterns
full-stack-skills/java-skills
MyBatis 核心 ORM 技能。覆盖 XML vs 注解 SQL选择、ResultMap复用(extends)、关联查询(association/collection join vs 嵌套select/N+1决策)、分页插件配置、和$的SQL注入防护、动态SQL(if/where/set/foreach/choose)最佳实践、columnPrefix解决同表多次JOIN。 当用户编写 MyBatis Mapper XML、处理关联查询、配置分页、防范SQL注入时使用。
java-conventions
full-stack-skills/java-skills
统一 Java 项目编码规范与注释规范(SLF4J+Lombok 日志、Bean Lombok 注解选择、判空 Objects/Optional、工具类优先级 Spring→Apache Commons→Hutool→Guava、复杂逻辑用设计模式/简单逻辑不拆分、Controller/Service/ServiceImpl/Mapper 注释一致性)。当需要“按 Java 规范重构/Review/补全注释/统一日志/统一工具类使用/补全 JavaDoc”时使用。
redis-redisson-patterns
full-stack-skills/java-skills
Redis + Redisson 缓存与分布式锁技能。覆盖缓存Key命名规范、过期时间设置原则、RedisTemplate序列化选择(JSON vs JDK vs String)、Redisson分布式锁三大模式(watchDog/tryLock 有leaseTime/无leaseTime 决策)、缓存穿透(布隆/空值缓存)/击穿(互斥锁)/雪崩(随机TTL)防护、Caffeine vs Redis选择决策。 纠正 LLM:不设过期时间、StringRedisTemplate和RedisTemplate混用、Redisson锁不 try-finally unlock、看门狗在指定 leaseTime 时不生效。
Popular backend & apis skills
find-skills
vercel-labs/skills
Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
entra-app-registration
microsoft/azure-skills
Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.
google-agents-cli-adk-code
google/agents-cli
This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).
embedded-captions
heygen-com/hyperframes
Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.
entra-agent-id
microsoft/azure-skills
Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).
neon
neondatabase/agent-skills
Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.