簡體   English   中英

Spring Boot 單元測試 MockMVC 拋出 BadRequest 即使存在 API

[英]Spring Boot Unit Test MockMVC throws BadRequest eventhough there exists API for it

我試圖為控制器 API quiz POST 方法編寫一個測試,它的 GET 調用工作正常,但不能 POST。

單元測試(失敗):

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

工作代碼

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM