/java-skills:junit-mockito-patternsfrom java-skills
JUnit5 + Mockito 测试模式技能:覆盖 @ExtendWith 迁移、@Mock/@InjectMocks 规则、FIRST 测试隔离原则、@SpringBootTest 与切片测试选择、BDDMockito 风格、ArgumentCaptor 与 verify 验证、@ParameterizedTest 参数化测试。
Ships in java-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
来源:https://junit.org/junit5/docs/current/user-guide/
Mockito:https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html
| 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) | 测试顺序 |
| # | 错误 | 正确做法 |
|---|---|---|
| 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));
}
}
@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());
}
}
@DataJpaTest
@DisplayName("用户仓库测试")
class UserRepositoryTest {
@Autowired TestEntityManager em;
@Autowired UserRepository repo;
@Test
@DisplayName("按用户名查询-存在-返回用户")
void findByUsername_Exists_ReturnUser() {
em.persistAndFlush(new User("zhang", "[email protected]"));
Optional<User> result = repo.findByUsername("zhang");
assertThat(result).isPresent();
assertThat(result.get().getEmail()).isEqualTo("[email protected]");
}
@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折
);
}
}
@Test
@DisplayName("注册用户-验证发送欢迎邮件")
void registerUser_ShouldSendWelcomeEmail() {
@Captor ArgumentCaptor<EmailMessage> emailCaptor;
given(mailClient.send(any())).willReturn(true);
userService.register("[email protected]", "张三");
then(mailClient).should().send(emailCaptor.capture());
EmailMessage msg = emailCaptor.getValue();
assertThat(msg.getTo()).isEqualTo("[email protected]");
assertThat(msg.getSubject()).contains("欢迎");
}
@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(慎用,仅关键流程)
assertThat(x).isEqualTo(y) 更可读、链式调用never() 或 times(0)methodName_StateUnderTest_ExpectedBehavior 或 @DisplayName 中文描述本技能不收集、存储或传输任何用户数据。
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Other plugins' skills for the same job
39 skills in this plugin
/caffeine-patternsCaffeine JVM 本地缓存技能。覆盖本地缓存 vs 远程缓存(Redis)选择决策树、expireAfterWrite vs expireAfterAccess vs refreshAfterWrite 三种过期策略对比与组合规则(refresh < expire)、CacheLoader加载与reload异步刷新模式、Spring Cache @Cacheable集成、maximumSize驱逐策略、recordStats缓存统计。 纠正 LLM:用 ConcurrentHashMap+手动过期、所有缓存走Redis、refreshAfterWrite > expireAfterWrite导致永远不刷新、CacheLoader返回null导致缓存穿透。/commons-patternsApache Commons 最佳实践模式。从官方文档提炼,覆盖 Commons Lang3(StringUtils千面判空/isEmpty vs isBlank/Validate抛NullPointerException迁移)、Commons IO(IOUtils.toString大文件陷阱/FileUtils.lineIterator逐行读模式/FilenameUtils.normalize路径规范化)、Commons Collections4(CollectionUtils.union/intersection/subtract集合运算)。 纠正 LLM 误用:混淆 StringUtils.isBlank vs isEmpty、IOUtils.toString 读大文件OOM、不知道 LineIterator 逐行读模式、用 lang 而非 lang3 包名。/Generated from the plugin's indexed repository (full-stack-skills/java-skills) — no native marketplace selected
npx claudepluginhub p/full-statck-skills-java-skills