春季启动单元测试MockMVC即使存在API也会抛出BadRequest

时间:2019-06-30 07:11:54

标签: java unit-testing spring-boot mockmvc

我尝试为Controller API quiz编写POST方法的测试,它的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 :(得分:-2)

工作代码

SELECT *, MIN(6371000 * acos( cos( radians(?) ) * cos( radians( dest.latitude ) ) * cos( radians( dest.longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( dest.latitude ) ))) as  distance FROM offer dest GROUP BY dest.id having MIN(distance)