为了账号安全,请及时绑定邮箱和手机立即绑定

在 Spring Boot 中使用 JUnit5 和 Mockito 进行集成测试

在 Spring Boot 中使用 JUnit5 和 Mockito 进行集成测试

智慧大石 2021-08-06 10:54:18
我在春季启动时遇到控制器测试问题。我在任何地方都找不到示例如何使用 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);  }
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 429 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信