Issue
I have below REST endpoint mapping.
@GetMapping("/employee/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable("id") int id) {
Employee employee = employeeRepository.getEmployeeById (id);
if(employee == null) {
throw new EmployeeNotFoundException ();
}
ResponseEntity<Employee> responseEntity = new ResponseEntity<Employee> (employee, HttpStatus.OK);
return responseEntity;
}
To test the failing path, I have the following test case.
@Test
public void getEmployeeFailTest() throws Exception {
Mockito.when (employeeRepository.getEmployeeById (Mockito.anyInt ())).thenReturn (null);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get ("/employee/10")
.accept (MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform (requestBuilder).andReturn ();
String response = result.getResponse ().getContentAsString ();
System.out.println (employeeRepository.getEmployeeById (5)==null);
String expected = "{\"errorCode\":1,\"message\":\"404: Employee not found!\"}";
JSONAssert.assertEquals (expected, response, false);
Assert.assertEquals (404, result.getResponse ().getStatus ());
}
In the repository class, I am returning the hardcoded Employee object.
public Employee getEmployeeById(int i) {
Employee employeeMock = new Employee (1, "XYZ","[email protected]",new Department (1, "HR"));
return employeeMock;
}
The test cases are passing successfully when I return null
in the above method. But with the above implementation, it fails.
Thanks to Mockito.when (employeeRepository.getEmployeeById (Mockito.anyInt ())).thenReturn (null);
getEmployeeById
is returning null
in test method but in controller's method above hardcoded Employee
object is getting returned
Am I missing something?
Solution
1) If I understand your test correctly then you expect "404 not found" in response to "employee/10". When you return null
then REST controller throws EmployeeNotFoundException
(which I assume handled via exception handler and converted to 404). When you return non-null object then exception is not thrown and test fails.
I suggest your repository class emulates object not found by
public Employee getEmployeeById(int i) {
return i==10 ? null : new Employee (1, "XYZ","[email protected]",new Department (1, "HR"));
}
2) Mockito.when (employeeRepository.getEmployeeById (Mockito.anyInt ())).thenReturn (null);
this code does not seem working. I assume you do not inject employeeRepository
to REST properly. You should mark it with @MockBean
in your test class so Spring Test will prefer it over real implementation
Answered By - Alexander Pavlov
Answer Checked By - Marie Seifert (JavaFixing Admin)