测试策略
JUnit 5 基础
单元测试
java
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
void testFindById() {
User user = new User();
user.setId(1L);
user.setUsername("testuser");
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
User found = userService.findById(1L);
assertNotNull(found);
assertEquals("testuser", found.getUsername());
verify(userRepository, times(1)).findById(1L);
}
}集成测试
java
@SpringBootTest
class UserIntegrationTest {
@Autowired
private UserService userService;
@Autowired
private UserRepository userRepository;
@Test
@Transactional
void testCreateAndFindUser() {
User user = new User();
user.setUsername("integrationuser");
user.setEmail("integration@example.com");
User saved = userService.save(user);
assertNotNull(saved.getId());
User found = userService.findById(saved.getId());
assertEquals("integrationuser", found.getUsername());
}
}MockMvc 测试
java
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("testuser"));
}
}返回第四章概览