2

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
Patan
  • 17,073
  • 36
  • 124
  • 198

2 Answers2

3

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 e.g.

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 ;)

Nikos T
  • 106
  • 1
  • 5
1

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);
Steve C
  • 18,876
  • 5
  • 34
  • 37