我在春季启动时遇到控制器测试问题。我在任何地方都找不到示例如何使用 junit5 和 mockito 进行 spring 控制器集成测试。我写过这样的东西:@ExtendWith(SpringExtension.class)@WebMvcTest(UserController.class)class UserControllerTest { @MockBean private UserService userService; @Autowired private MockMvc mockMvc; private User user; @BeforeEach void init(){ user = getUserData(); } private User getUserData(){ User u = new User(); u.setId(0); return u; } @Test void shouldReturnDefaultMessage() throws Exception { int id = 0; when(userService.findById(id)).thenReturn(Optional.ofNullable(user)); this.mockMvc.perform(get("/user/" + id)) .andDo(print()) .andExpect(status() .isOk()) .andExpect(jsonPath("$.id", is(String.valueOf(id)))); }}UserController.class:@RestController@RequestMapping(value = "/user") public class UserController { private final UserService userService; private final ConverterContext converterContext; public UserController(UserService userService, ConverterContext converterContext) { this.userService = userService; this.converterContext = converterContext; } @RequestMapping(value = "", method = RequestMethod.GET) public ResponseEntity get(@RequestParam(value = "username", required = false) @ExistAccountWithUsername String username) { if(!username.isEmpty()){ return getUsersByUsername(username); } return getAllUsers(); } private ResponseEntity getUsersByUsername(String username){ Optional<User> user = userService.findByUsername(username); ShowUserDto showUserDto = convert(user.get()); return new ResponseEntity<>(showUserDto, HttpStatus.OK); } private ResponseEntity getAllUsers(){ List<User> users = userService.findAll(); List<ShowUserDto> showUserDtos = users.stream() .map(this::convert) .collect(Collectors.toList()); return new ResponseEntity<>(showUserDtos, HttpStatus.OK); }
添加回答
举报
0/150
提交
取消