java-testing by pluginagentmarketplace/custom-plugin-java
npx skills add https://github.com/pluginagentmarketplace/custom-plugin-java --skill java-testing使用现代测试实践为 Java 应用程序编写全面的测试。
本技能涵盖使用 JUnit 5、Mockito、AssertJ 进行 Java 测试,以及使用 Spring Boot Test 和 Testcontainers 进行集成测试。包括 TDD 模式和测试覆盖率策略。
在以下情况下使用:
// Unit Test with Mockito
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
@DisplayName("Should find user by ID")
void shouldFindUserById() {
// Given
User user = new User(1L, "John");
given(userRepository.findById(1L)).willReturn(Optional.of(user));
// When
Optional<User> result = userService.findById(1L);
// Then
assertThat(result)
.isPresent()
.hasValueSatisfying(u ->
assertThat(u.getName()).isEqualTo("John"));
then(userRepository).should().findById(1L);
}
}
// Parameterized Test
@ParameterizedTest
@CsvSource({
"valid@email.com, true",
"invalid-email, false",
"'', false"
})
void shouldValidateEmail(String email, boolean expected) {
assertThat(validator.isValid(email)).isEqualTo(expected);
}
// Integration Test with Testcontainers
@Testcontainers
@SpringBootTest
class OrderRepositoryIT {
@Container
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:15");
@DynamicPropertySource
static void configure(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
private OrderRepository repository;
@Test
void shouldPersistOrder() {
Order saved = repository.save(new Order("item", 100.0));
assertThat(saved.getId()).isNotNull();
}
}
// API Test with MockMvc
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void shouldReturnUser() throws Exception {
given(userService.findById(1L))
.willReturn(Optional.of(new User(1L, "John")));
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"));
}
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
public class UserTestBuilder {
private Long id = 1L;
private String name = "John Doe";
private String email = "john@example.com";
private boolean active = true;
public static UserTestBuilder aUser() {
return new UserTestBuilder();
}
public UserTestBuilder withName(String name) {
this.name = name;
return this;
}
public UserTestBuilder inactive() {
this.active = false;
return this;
}
public User build() {
return new User(id, name, email, active);
}
}
// Usage
User user = aUser().withName("Jane").inactive().build();
<!-- JaCoCo configuration -->
<configuration>
<rules>
<rule>
<element>BUNDLE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.80</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
| 问题 | 原因 | 解决方案 |
|---|---|---|
| 模拟对象不工作 | 缺少 @ExtendWith | 添加 MockitoExtension |
| 测试中出现 NPE | 模拟对象未初始化 | 检查 @InjectMocks |
| 测试不稳定 | 共享状态 | 隔离测试数据 |
| 上下文失败 | 缺少 Bean | 使用 @MockBean |
□ 单独运行单个测试
□ 检查模拟设置是否与调用匹配
□ 验证 @BeforeEach 设置
□ 检查 @Transactional 边界
□ 检查是否存在共享可变状态
Skill("java-testing")
java-testing-advanced - 高级模式java-spring-boot - Spring 测试切片每周安装量
435
代码仓库
GitHub 星标数
27
首次出现
2026年1月21日
安全审计
安装于
opencode367
codex342
gemini-cli336
github-copilot320
cursor280
kimi-cli278
Write comprehensive tests for Java applications with modern testing practices.
This skill covers Java testing with JUnit 5, Mockito, AssertJ, and integration testing with Spring Boot Test and Testcontainers. Includes TDD patterns and test coverage strategies.
Use when you need to:
// Unit Test with Mockito
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
@DisplayName("Should find user by ID")
void shouldFindUserById() {
// Given
User user = new User(1L, "John");
given(userRepository.findById(1L)).willReturn(Optional.of(user));
// When
Optional<User> result = userService.findById(1L);
// Then
assertThat(result)
.isPresent()
.hasValueSatisfying(u ->
assertThat(u.getName()).isEqualTo("John"));
then(userRepository).should().findById(1L);
}
}
// Parameterized Test
@ParameterizedTest
@CsvSource({
"valid@email.com, true",
"invalid-email, false",
"'', false"
})
void shouldValidateEmail(String email, boolean expected) {
assertThat(validator.isValid(email)).isEqualTo(expected);
}
// Integration Test with Testcontainers
@Testcontainers
@SpringBootTest
class OrderRepositoryIT {
@Container
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:15");
@DynamicPropertySource
static void configure(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired
private OrderRepository repository;
@Test
void shouldPersistOrder() {
Order saved = repository.save(new Order("item", 100.0));
assertThat(saved.getId()).isNotNull();
}
}
// API Test with MockMvc
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void shouldReturnUser() throws Exception {
given(userService.findById(1L))
.willReturn(Optional.of(new User(1L, "John")));
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"));
}
}
public class UserTestBuilder {
private Long id = 1L;
private String name = "John Doe";
private String email = "john@example.com";
private boolean active = true;
public static UserTestBuilder aUser() {
return new UserTestBuilder();
}
public UserTestBuilder withName(String name) {
this.name = name;
return this;
}
public UserTestBuilder inactive() {
this.active = false;
return this;
}
public User build() {
return new User(id, name, email, active);
}
}
// Usage
User user = aUser().withName("Jane").inactive().build();
<!-- JaCoCo configuration -->
<configuration>
<rules>
<rule>
<element>BUNDLE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0.80</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
| Problem | Cause | Solution |
|---|---|---|
| Mock not working | Missing @ExtendWith | Add MockitoExtension |
| NPE in test | Mock not initialized | Check @InjectMocks |
| Flaky test | Shared state | Isolate test data |
| Context fails | Missing bean | Use @MockBean |
□ Run single test in isolation
□ Check mock setup matches invocation
□ Verify @BeforeEach setup
□ Review @Transactional boundaries
□ Check for shared mutable state
Skill("java-testing")
java-testing-advanced - Advanced patternsjava-spring-boot - Spring test slicesWeekly Installs
435
Repository
GitHub Stars
27
First Seen
Jan 21, 2026
Security Audits
Gen Agent Trust HubFailSocketPassSnykPass
Installed on
opencode367
codex342
gemini-cli336
github-copilot320
cursor280
kimi-cli278
Vue.js测试最佳实践:Vue 3组件、组合式函数、Pinia与异步测试完整指南
3,700 周安装