使用mockito时的Classcastexception

时间:2014-08-04 14:15:30

标签: java junit mockito junit4

我在测试用例中使用以下代码来获取classcast异常。

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

我想把它概括为

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

我做错了吗?

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

2 个答案:

答案 0 :(得分:1)

如果您在使用Mockito时发现需要进行类型转换,那么通常会出现问题。

我想你正在尝试做类似的事情:

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

答案 1 :(得分:0)

嗨,我知道这是一个非常老的问题,但是今天我自己还是遇到了这个问题。

无论如何,这都与hamcrest如何处理Matchers有关。我基本上不返回给定的类型,而是围绕它的包装。

最简单的解决方法是使用来自模仿者的任何东西,例如hamprest。

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

有关更多详细信息,请参见以下答案:comparison with mockito and hamcrest matchers

希望它可以帮助绊脚的人;)

相关问题