Reputation: 569
I am new to mockito testing. I am trying to learn and could not find answer for my specific problem.
I have method as below in one of the Controller
@RequestMapping(value = /employer, method = RequestMethod.POST,
consumes = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public HttpStatus saveEmployerInfo (@Valid @RequestBody EmployerInfo empInfo,
HttpServletRequest request)
{
String employeeId = (String) request.getAttribute(EMP_ATTRIBUTE);
employerService.processEmpInfo(empInfo, employeeId);
return HttpStatus.OK;
}
I am trying to do below in mockito:
EmployerInfo mockEmpInfo = mock(EmployerInfo.class);
HttpServletRequest mockHttpServletRequest = mock(HttpServletRequest.class);
Controller mockController = mock(Controller.class);
when(mockController.saveEmployerInfo(Matchers.any(EmployerInfo.class), (HttpServletRequest) any(HttpServletRequest.class))).thenReturn(HttpStatus.OK);
HttpStatus responseStatus = mockController.saveEmployerInfo(Matchers.any(EmployerInfo.class),
(HttpServletReq(mockEmpInfo, mockHttpServletRequest);
assertEquals(HttpStatus.OK, responseStatus.OK);
I am still getting below errors and not able to solve this issue :
java.lang.ClassCastException: org.hamcrest.core.IsInstanceOf cannot be cast to com.xxx.model.EmployerInfo
Upvotes: 0
Views: 1238
Reputation: 7526
If you want to test your controller, you have to do it on a real instance and not a mocked instance. Assuming your controller looks something like this:
@Controller
public class EmployerController {
@Autowire
EmployerService employerService;
@RequestMapping(value = /employer, method = RequestMethod.POST,
consumes = { MediaType.APPLICATION_JSON_UTF8_VALUE })
public HttpStatus saveEmployerInfo (@Valid @RequestBody EmployerInfo empInfo,
HttpServletRequest request) {
String employeeId = (String) request.getAttribute(EMP_ATTRIBUTE);
employerService.processEmpInfo(empInfo, employeeId);
return HttpStatus.OK;
}
}
Then the test could look like this (with Juni4):
@RunWith(MockitoJUnitRunner.class)
public class EmployerControllerTest {
@Mock
private EmployerService employerService;
@InjectMocks
private EmployerController controller;
@Test
public void shouldReturnHttpStatusOk() {
// Given
EmployerInfo mockEmpInfo = mock(EmployerInfo.class);
HttpServletRequest mockHttpServletRequest = mock(HttpServletRequest.class);
String employerId = "employerId"
when(mockHttpServletRequest.getAttribute(EMP_ATTRIBUTE)).willReturn(employerId);
// When
HttpStatus status = controller.saveEmployerInfo(mockEmpInfo, mockHttpServletRequest);
// Then
verify(employerService).processEmpInfo(mockEmpInfo, employerId);
assertEquals(HttpStatus.OK, status);
}
}
Upvotes: 1