简体   繁体   中英

Classcast exception when using mockito

I am getting classcast exception using the following bit of code in Test case.

  Employee employee1= new Employee();
  Employee employee2= new Employee();
  Employee employee3= new Employee();
  int id=1234;

  when(employee1.getID()).thenReturn(id);
  when(employee2.getID()).thenReturn(id);
  when(employee3.getID()).thenReturn(id);

I want to generalize this as

 when((((Employee)Matchers.any(Employee.class)).getID())).thenReturn(id);

Am I doing anything wrong?

java.lang.ClassCastException: org.hamcrest.core.IsInstanceOf cannot be cast to com.site.model.Employee

If you find that you need to typecast when using Mockito then you usually have something wrong.

I guess you are trying to do something like:

    Employee employee = Mockito.mock(Employee.class);
    when(employee.getId()).thenReturn(id);

Hi I know this is a very old question however I just got to this same problem myself today.

Anyway it has to do with how hamcrest handles Matchers. I basically doesn't return the given type but a wrapper around it.

The easiest way to fix it is to use any from mockito not hamcrest eg

when((((Employee)org.mockito.Matchers.any(Employee.class)).getID())).thenReturn(id); 

For more details see this answer: comparison with mockito and hamcrest matchers

Hope it helps anyone stumbling through this ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM