Модульный тест Spring Boot MockMVC генерирует событие BadRequest, хотя для него существует API - PullRequest
0 голосов
/ 30 июня 2019

Я попытался написать тест для метода POST для API контроллера quiz Его вызов GET работает правильно, но не POST.

UnitTest (сбой):

private static final String url = "/quiz";
.
.
.

@Test
    public void addQuiz_withValidDetails_shouldReturnQuizObject() throws Exception {
        QuizDTO quizDTO = new QuizDTO();
        quizDTO.setQuizId("QuizId");
        quizDTO.setCategoryName("CatName");
        quizDTO.setQuizUserId("QuizUserId");
        quizDTO.setQuizType(QuizType.NORMAL);
        quizDTO.setEndDateTime(LocalDateTime.now());
        quizDTO.setStartDateTime(LocalDateTime.now());

        this.mockMvc.perform(
                post(url)
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(asJsonString(quizDTO)))
                .andDo(print())
                .andExpect(status().isCreated());
    }

Контроллер:

@RequestMapping("/quiz")
.
.
.
@ResponseStatus(code = HttpStatus.CREATED)
    @RequestMapping(method = RequestMethod.POST)
    public QuizDTO addQuiz(@RequestBody QuizDTO quizDTO) throws CategoryNotFoundException, QuizUserNotFoundException, QuizNotFoundException, QuizAlreadyExistsException {
        QuizDTO.convertToDTO(this.quizService.addQuiz(
                quizDTO.getQuizId(),
                quizDTO.getCategoryName(),
                quizDTO.getQuizUserId(),
                quizDTO.getQuizType(),
                quizDTO.getStartDateTime(),
                quizDTO.getEndDateTime()));

        return this.getQuiz(quizDTO.getQuizId());
    }

Ошибка:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /quiz
       Parameters = {}
          Headers = [Content-Type:"application/json", Accept:"application/json"]
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.quizroulette.Controller.QuizController
           Method = public com.quizroulette.DTO.QuizDTO com.quizroulette.Controller.QuizController.addQuiz(com.quizroulette.DTO.QuizDTO) throws com.quizroulette.Exception.CategoryNotFoundException,com.quizroulette.Exception.QuizUserNotFoundException,com.quizroulette.Exception.QuizNotFoundException,com.quizroulette.Exception.QuizAlreadyExistsException

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /quiz
       Parameters = {}
          Headers = [Content-Type:"application/json", Accept:"application/json"]
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.quizroulette.Controller.QuizController
           Method = public com.quizroulette.DTO.QuizDTO com.quizroulette.Controller.QuizController.addQuiz(com.quizroulette.DTO.QuizDTO) throws com.quizroulette.Exception.CategoryNotFoundException,com.quizroulette.Exception.QuizUserNotFoundException,com.quizroulette.Exception.QuizNotFoundException,com.quizroulette.Exception.QuizAlreadyExistsException

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status 
Expected :201
Actual   :400

1 Ответ

0 голосов
/ 30 июня 2019

Рабочий код

mvc.perform( MockMvcRequestBuilders
      .post("/users")
      .content(asJsonString(new UserVO(null, "firstName4", "lastName4", 
  "user1@yahoo.com")))
      .contentType(MediaType.APPLICATION_JSON)
      .accept(MediaType.APPLICATION_JSON))
      .andExpect(status().isCreated())
      .andExpect(MockMvcResultMatchers.jsonPath("$.userId").exists());
    enter code here

  <br>
# I think the issue is with parsing to json.  check content parsing in the above code.
...