0

I am unable to test the post request for MockMvc in spring boot

@PostMapping(path = "/add", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Student> addStudent(@RequestBody Student student) {
    try{
        Student saveStudent = studentService.addStudent(student);
        return ResponseEntity.ok(saveStudent);
    }  catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

}

The test case:

@Autowired
MockMvc mockMvc;

@Mock
StudentService studentService;

@InjectMocks
StudentController studentController;

@BeforeEach
void setUp() {
    mockMvc = MockMvcBuilders.standaloneSetup(studentController).build();
}


@Test
@Order(1)
void addStudent() throws Exception {
    Student student = new Student(1, "Test", "Test", "Test");
    when(studentService.addStudent(student)).thenReturn(student);
    ObjectMapper mapper = new ObjectMapper();
    String jsonBody = mapper.writeValueAsString(student);
    this.mockMvc.perform(post("/student/add").content(jsonBody).contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andDo(print());
}

The test cases for get requests are working but i am getting the following exception while running this test case:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class com.example.models.Student]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of com.example.models.Student (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: (PushbackInputStream); line: 1, column: 2]

at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)

Diluted Dev
  • 45
  • 1
  • 9
  • Does this answer your question? [No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator](https://stackoverflow.com/questions/53191468/no-creators-like-default-construct-exist-cannot-deserialize-from-object-valu) – Jens Feb 24 '22 at 08:41
  • @Jens, thanks, needed to add a default constructor in model class. – Diluted Dev Feb 24 '22 at 09:11

0 Answers0