猿问

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

我在春季启动时遇到控制器测试问题。我在任何地方都找不到示例如何使用 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);

  }


智慧大石
浏览 430回答 1
1回答
随时随地看视频慕课网APP

相关分类

Java
我要回答