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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Cool answer! The only change is to use org.mockito.ArgumentMatchers.any as org.mockito.Matchers.any is deprecated.
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);

5 Comments

Here employee is not fixed. I need to return same thing for the instance employee1 or employee2. Can you suggest how to do that
You should show more of your test code so that we can get some context
Sorry for limited information. I have updated the question. Can you help me.
What piece of logic are you trying to test?
It shall be independent of logic. I just need to return a constant value when the method is being invoked for all test cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.