samedi 5 décembre 2020

MockMVC JsonPath response has empty body?

Testing the controller gives following error: java.lang.AssertionError: No value at JSON path "$.firstName". Apparently the body of my response is empty for some reason. Controller is a RestController and and i'm correctly mocking the service. Can someone help me ?

Testclass:

@WebMvcTest(EmployeeController.class)
class EmployeeControllerTest {
    Employee employee = new Employee();

    @Autowired
    private MockMvc mvc;

    @MockBean
    private EmployeeServiceImpl service;


    @BeforeEach
    public void initEmployee() {
        employee.setFirstName("John");
        employee.setLastName("Doe");
        employee.setPlace("xxxx");
        employee.setEmployeeTitle(EmployeeTitle.SENIOR_JAVA_DEVELOPER);
        employee.setEmployeeId(1L);

    }

    @Test
    public void createEmployeeAPI() throws Exception {

        when(service.addNewEmployee(employee)).thenReturn(employee);

        mvc.perform(MockMvcRequestBuilders
                .post("/employees")
                .content(asJsonString(employee))
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.firstName").value("John"));

    }

Request is correct but apparently the body is of the response is empty (see console output below):

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /employees
       Parameters = {}
          Headers = [Content-Type:"application/json;charset=UTF-8", Accept:"application/json", Content-Length:"124"]
             Body = {"employeeId":1,"firstName":"John","lastName":"Doe","employeeTitle":"SENIOR_JAVA_DEVELOPER","place":"xxxx","photoURrl":null}
    Session Attrs = {}

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Controller code:

@RestController
@RequestMapping("/employees")
public class EmployeeController extends ExceptionHandling {
    private final EmployeeService employeeService;

    @Autowired
    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @PostMapping()
    public Employee addEmployee(@RequestBody Employee employee) {
        return employeeService.addNewEmployee(employee);
    }

Aucun commentaire:

Enregistrer un commentaire