Spring Data JPA是Spring框架中用于简化JPA(Java Persistence API)开发的模块,它通过Repository接口自动实现常见的CRUD操作,减少了样板代码。
MockMvc是Spring Test模块提供的工具,用于模拟HTTP请求并对控制器(Controller)进行单元测试,无需启动完整的HTTP服务器。
JUnit是Java生态中最流行的单元测试框架,Spring Boot Test基于JUnit提供了额外的测试支持。
原因:可能未正确配置测试的数据库或未启用JPA测试支持
解决方案:
@SpringBootTest
@DataJpaTest
@AutoConfigureMockMvc
public class UserControllerTest {
// 测试代码
}
原因:可能URL路径不正确或控制器未正确映射
解决方案:
mockMvc.perform(get("/api/users").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
原因:测试类可能未配置事务支持
解决方案:
@SpringBootTest
@Transactional
@AutoConfigureMockMvc
public class UserServiceTest {
// 测试代码
}
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserRepository userRepository;
@Test
public void testGetUserById() throws Exception {
User mockUser = new User(1L, "test@example.com", "Test User");
when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Test User"));
}
}
@SpringBootTest
@AutoConfigureMockMvc
@DataJpaTest
public class UserControllerIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private UserRepository userRepository;
@Test
@Transactional
public void testCreateUser() throws Exception {
String userJson = "{\"email\":\"new@example.com\",\"name\":\"New User\"}";
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(userJson))
.andExpect(status().isCreated());
User savedUser = userRepository.findByEmail("new@example.com");
assertNotNull(savedUser);
assertEquals("New User", savedUser.getName());
}
}
@Test
public void testGetUserNotFound() throws Exception {
when(userRepository.findById(anyLong())).thenReturn(Optional.empty());
mockMvc.perform(get("/api/users/999"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.message").value("User not found"));
}
@Test
@WithMockUser(username = "admin", roles = {"ADMIN"})
public void testAdminEndpoint() throws Exception {
mockMvc.perform(get("/api/admin/users"))
.andExpect(status().isOk());
}
@Test
public void testUnauthorizedAccess() throws Exception {
mockMvc.perform(get("/api/admin/users"))
.andExpect(status().isUnauthorized());
}
通过结合Spring Data JPA和MockMvc,可以构建全面而高效的Spring Boot应用测试套件,覆盖从数据持久层到API层的各种测试场景。
没有搜到相关的文章