我有一个我试图模拟的数据库访问对象。使用模拟的代码调用public void refresh(Project project)
方法。我需要操纵参数并插入'id。'
错误:
SEVERE - EjbTransactionUtil.handleSystemException: websphere.jaxrs.entities.Project cannot be cast to java.lang.Boolean
java.lang.ClassCastException: websphere.jaxrs.entities.Project cannot be cast to java.lang.Boolean
at websphere.jaxrs.daos.interfaces.ProjectDAO$$EnhancerByMockitoWithCGLIB$$cf2a39e4.insert(<generated>)
at websphere.jaxrs.service.ProjectREST.postProject(ProjectREST.java:105)
测试:
@Test
public void postProject_ValidRequest_NoContent() {
projectRest = (ProjectREST) container.getContext().lookup("java:global/ProjectREST");
projectDAOm = mock(ProjectDAO.class, Mockito.RETURNS_DEFAULTS);
userDAOm = mock(UserDAO.class);
apiDAOm = mock(ApiDAO.class);
apikeyGeneratorm = mock(ApikeyGenerator.class);
projectRest.setDAO(projectDAOm, ProjectDAO.class); //override the real implementation
projectRest.setDAO(userDAOm, UserDAO.class);
projectRest.setDAO(apiDAOm, ApiDAO.class);
projectRest.setDAO(apikeyGeneratorm, ApikeyGenerator.class);
Integer keyLength = 40;
when(projectDAOm.insert((Project) anyObject())).thenAnswer(new Answer<Project>() {
@Override
public Project answer(InvocationOnMock invocation) throws Throwable {
Project project = (Project) invocation.getArguments()[0];
project.setProjectid(10000);
project.setCollaborators(new ArrayList<Collaborator>());
project.setActiveapis(new ArrayList<Api>());
return project;
}
});
Map<String, Object> projectSettings = new HashMap<String, Object>();
projectSettings.put("projectname", "Hello World");
Response response = projectRest.postProject("user", projectSettings);
assertEquals(204, response.getStatus());
verify(projectDAOm, atLeastOnce()).insert(new Project());
verify(apikeyGeneratorm, times(1)).generateKey(anyInt(), keyLength);
}
正在测试的课程内:
public Response postProject(String user, Map<String, Object> data) {
Project project = new Project();
project.setProjectname((String) data.get("projectname"));
User owner = userDAO.findById(user);
project.setOwner(owner);
projectDAO.insert(project); // ERROR OCCURS HERE
Collaborator c = new Collaborator(owner, project);
project.getCollaborators().add(c);
owner.getOwnedProjects().add(project);
owner.getCollaboratingProjects().add(c);
Apikey apikey = new Apikey(apikeyGenerator.generateKey(project.getProjectid(), API_KEY_LENGTH));
project.setApikey(apikey);
apikey.setProject(project);
apikey.setTimestamp(new Timestamp(Calendar.getInstance().getTimeInMillis()));
projectDAO.insert(project);
return Response.status(204).build();
}
答案 0 :(得分:1)
如果insert
与refresh
具有相同的签名,则该方法返回null
。因此,您应使用when(...).thenAnswer
doAnswer(new Answer<Void>(){...}).when(mock).method()