JUnit 5, Mockito, Spring test slices, integration testing, and test organization.
class UserServiceTest {
@Test
@DisplayName("should create user with valid data")
void shouldCreateUser() {
// Given
var request = new CreateUserRequest("John", "john@example.com");
// When
var user = userService.create(request);
// Then
assertThat(user.getName()).isEqualTo("John");
assertThat(user.getEmail()).isEqualTo("john@example.com");
}
@ParameterizedTest
@ValueSource(strings = {"", " ", "invalid"})
void shouldRejectInvalidEmail(String email) {
var request = new CreateUserRequest("John", email);
assertThatThrownBy(() -> userService.create(request))
.isInstanceOf(ValidationException.class);
}
@BeforeEach
void setUp() {
// Setup before each test
}
@AfterEach
void tearDown() {
// Cleanup after each test
}
}
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
OrderRepository orderRepository;
@Mock
InventoryService inventoryService;
@InjectMocks
OrderService orderService;
@Test
void shouldCreateOrder() {
// Given
var request = new CreateOrderRequest("product-1", 2);
when(inventoryService.checkStock("product-1")).thenReturn(true);
when(orderRepository.save(any())).thenAnswer(inv -> inv.getArgument(0));
// When
var order = orderService.create(request);
// Then
assertThat(order).isNotNull();
verify(inventoryService).checkStock("product-1");
verify(orderRepository).save(any(Order.class));
}
}
// Full context
@SpringBootTest
class ApplicationTests {}
// Web layer only
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mockMvc;
@MockBean UserService userService;
@Test
void shouldReturnUser() throws Exception {
when(userService.findById(1L)).thenReturn(Optional.of(new User(1L, "John")));
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"));
}
}
// JPA layer only
@DataJpaTest
class UserRepositoryTest {
@Autowired UserRepository repository;
@Autowired TestEntityManager entityManager;
@Test
void shouldFindByEmail() {
entityManager.persist(new User("john@example.com"));
var user = repository.findByEmail("john@example.com");
assertThat(user).isPresent();
}
}
npx skills add ngxtm/Testing with JUnit & Mockito下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer