Java Mockito中的ClassCastException

Java Mockito中的ClassCastException,java,mockito,Java,Mockito,我尝试使用Mockito编写以下方法的单元测试。我对莫基托还不太熟悉,正在努力赶上 测试方法 Mockito的单元测试 @Test public void testRestHandler() throws Exception { RestHandler handler = spy(new RestHandler()); RestClient mockClient = Mockito.mock(RestClient.class,Mockito.RETURNS_DEEP_STUBS)

我尝试使用Mockito编写以下方法的单元测试。我对莫基托还不太熟悉,正在努力赶上

测试方法 Mockito的单元测试

@Test
public void testRestHandler() throws Exception {
    RestHandler handler = spy(new RestHandler());
    RestClient mockClient = Mockito.mock(RestClient.class,Mockito.RETURNS_DEEP_STUBS); 
    Resource mockResource = Mockito.mock(Resource.class,Mockito.RETURNS_DEEP_STUBS);

    doReturn(mockClient).when(handler).getClient();
    Mockito.when(mockClient.resource(Mockito.anyString())).thenReturn(mockResource);

  //ClassCastException at the below line
    Mockito.when(mockResource.contentType(Mockito.anyString()).accept(Mockito.anyString()).get(Mockito.eq(String.class))).thenReturn("dummy read result");

    handler.setRequestType(MediaType.APPLICATION_FORM_URLENCODED);
    handler.setResponseType(MediaType.APPLICATION_JSON);
    handler.executeReadRequest("abc");
}
但我在排队时遇到了一个ClassCastException

Mockito.when(mockResource.contentType(Mockito.anyString()).accept(Mockito.anyString()).get(Mockito.eq(String.class))).thenReturn("dummy read result");
例外情况

java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$4b441c4d cannot be cast to java.lang.String
感谢您为解决此问题提供的任何帮助


非常感谢。

通过将get调用更改为解决了此问题

get(Mockito.any(Class.class))

存根期间的这种链接方式不正确:

Mockito.when(
    mockResource.contentType(Mockito.anyString())
        .accept(Mockito.anyString())
        .get(Mockito.eq(String.class)))
    .thenReturn("dummy read result");
尽管您已经将mock设置为返回深存根,但这一行并没有达到您认为的效果。所有三个匹配器(
anyString
anyString
eq
)都会在调用
when
的过程中进行评估,您的代码可能会在最轻微的挑衅下抛出
InvalidUseOfMatchersException
,包括添加不相关的代码或稍后的验证

这意味着您的问题不是使用
eq(String.class)
:而是Mockito试图在不属于它的地方使用类匹配器

相反,您需要特别注意:

Mockito.when(mockResource.contentType(Mockito.anyString()))
    .thenReturn(mockResource);
Mockito.when(mockResource.accept(Mockito.anyString()))
    .thenReturn(mockResource);
Mockito.when(mockResource.get(Mockito.eq(String.class))) // or any(Class.class)
    .thenReturn("dummy read response");

注意,这里的一些困难是使用构建器模式,这在Mockito中可能很费劲。(我在这里返回了
mockResource
,但是您可以想象返回特定的其他资源对象,代价是以后需要它们完全按顺序返回。)更好的方法可能是这样做。

虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,只使用代码的答案是没有用的。
Mockito.when(mockResource.contentType(Mockito.anyString()))
    .thenReturn(mockResource);
Mockito.when(mockResource.accept(Mockito.anyString()))
    .thenReturn(mockResource);
Mockito.when(mockResource.get(Mockito.eq(String.class))) // or any(Class.class)
    .thenReturn("dummy read response");