0

I have problem with unit test for controller that has to update an employee in REST-API. For testing I use mockito, JUnit, hamcrest. I am only posting the most important parts of these classes.

controller method

@PutMapping("{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long id,
                                               @RequestBody Employee employee) {
    return new ResponseEntity<>(employeeService.UpdateEmployee(id, employee), HttpStatus.OK);
}

service methods

@Override
public Employee UpdateEmployee(Long employeeId, Employee employee) {
    Employee employeeById = employeeRepository.findById(employeeId)
            .orElseThrow(() -> new ResourceNotFoundException("Employee with id " + employeeId + " not found"));

    employeeById.setFirstName(employee.getFirstName());
    employeeById.setLastName(employee.getLastName());
    employeeById.setEmail(employee.getEmail());
    employeeRepository.save(employeeById);
    return employeeById;
}

@Override
public Optional<Employee> getEmployeeById(Long id) {
    return employeeRepository.findById(id);
}

unit test

@BeforeEach
public void setup() {
    employee = Employee.builder()
            .firstName(TEST_FIRST_NAME)
            .lastName(TEST_LAST_NAME)
            .email(TEST_EMAIL)
            .build();
}

@Test
public void givenUpdatedEmployee_whenUpdateEmployee_thenReturnUpdateEmployeeObject() throws Exception {

        //given
        Long employeeId = 1L;

        Employee employeeInfo = Employee.builder()
                .firstName(NEW_TEST_FIRST_NAME)
                .lastName(NEW_TEST_LAST_NAME)
                .email(NEW_TEST_EMAIL)
                .build();

        BDDMockito.given(employeeService.getEmployeeById(employeeId))
                .willReturn(Optional.of(employee));

        BDDMockito.given(employeeService.UpdateEmployee(employeeId, employeeInfo))
                .willAnswer((invocationOnMock -> invocationOnMock.getArgument(0)));


        //when
        ResultActions response = mockMvc.perform(put("/api/v1/employees/{id}", employeeId)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsBytes(employeeInfo)));

        //then
        response.andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.firstName", is(employeeInfo.getFirstName())))
                .andExpect(jsonPath("$.lastName", is(employeeInfo.getLastName())))
                .andExpect(jsonPath("$.email", is(employeeInfo.getEmail())));
    }

receives an error java.lang.AssertionError: No value at JSON path "$.firstName"

Dratewka
  • 57
  • 1
  • 6

0 Answers0