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)