我是模仿测试的新手。我正在尝试学习,但找不到针对我特定问题的答案。
我在控制器之一中具有以下方法
@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;
}
我正在尝试在模仿中执行以下操作:
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);
我仍然遇到错误,无法解决此问题:
java.lang.ClassCastException: org.hamcrest.core.IsInstanceOf cannot be cast to com.xxx.model.EmployerInfo
答案 0 :(得分:1)
如果要测试控制器,则必须在真实实例而不是模拟实例上进行。假设您的控制器看起来像这样:
@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;
}
}
然后测试可能看起来像这样(使用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);
}
}