Springboot @Test 给Controller接口 写 单元测试
假设我们要测试以下Controller:
@RestController
@RequestMapping("/api/v1")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.getUserById(id);
if (user == null) {
return ResponseEntity.notFound().build();
} else {
return ResponseEntity.ok(user);
}
}
}
我们可以使用SpringBootTest和MockMvc来编写单元测试:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTests {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
public void testGetUserById() throws Exception {
Long userId = 1L;
User user = new User();
user.setId(userId);
user.setName("Alice");
given(userService.getUserById(userId)).willReturn(user);
mockMvc.perform(get("/api/v1/users/{id}", userId))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(userId.intValue())))
.andExpect(jsonPath("$.name", is(user.getName())));
}
}
在这个测试中,我们使用了MockBean来模拟UserService服务,使用given和willReturn方法来指定UserService在调用getUserById方法时返回我们指定的User。然后使用mockMvc.perform模拟一个GET请求,并使用andExpect来验证响应的状态码和响应体的内容。