-1

I have attempted to write a test for POST method for the Controller API quiz Its GET call work correctly but not POST.

UnitTest(fails):

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());
    }

Controller:

@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());
    }

Error:

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
Smit
  • 2,078
  • 2
  • 17
  • 40
  • Have you done any debugging? Do you know where the problem is? Before it reaches the controller? In addQuiz? In getQuiz? Outside the controller entirely? – jonrsharpe Jun 30 '19 at 07:20
  • @jonrsharpe Yes, I have done debugging. It does not reach addQuiz code at all. – Smit Jun 30 '19 at 07:21
  • Have you looked at the JSON you're generating? Does the same request work from another client (e.g. postman)? – jonrsharpe Jun 30 '19 at 07:22
  • alright found the problem. The LocalDateTime is being coverted into a sub object. that is causing the problem. – Smit Jun 30 '19 at 07:30
  • check this https://stackoverflow.com/questions/21648921/mocmvc-giving-httpmessagenotreadableexception – Suresh Kumar Jun 30 '19 at 07:37

1 Answers1

-2

Working code

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.
Community
  • 1
  • 1
Suresh Kumar
  • 90
  • 1
  • 9