ClassCastException using Mockito



我正在使用Mockito编写一个JUnit测试用例来测试JSONParseException,但我得到了ClassCastException。问题似乎在中

 when(response.readEntity(Mockito.any(Class.class))).thenReturn(baseModel);

下面是我的模拟课。

public class MockJerseyClient {
private ClientConfiguration clientConfig;
private Client client;
private WebTarget webTarget;
private Invocation.Builder invocationBuilder;
private Response response;
private StatusType statusType;
private String myString = null;
public enum CATEGORY {
    XML, JSON
}
private JAXBContext getContext(BaseModel baseModel) throws JAXBException {
    if (baseModel instanceof RetrieveBillingResponse) {
        return JAXBContext.newInstance(RetrieveBillingResponse.class);
    } else if (baseModel instanceof ThirdPartyVinResponse) {
        return JAXBContext.newInstance(ThirdPartyVinResponse.class);
    }
    return null;
}
public MockJerseyClient(String URI, int status, String contentType, BaseModel baseModel, CATEGORY responseType) throws EISClientException, Exception {
    if (responseType == CATEGORY.XML) {
        JAXBContext context = getContext(baseModel);
        Marshaller marshallerObj = context.createMarshaller();
        marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        marshallerObj.marshal(baseModel, byteOut);
        // myString = byteOut.toString();
        // System.out.println(myString);
    } else if (responseType == CATEGORY.JSON) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(stream, baseModel);
    }
    clientConfig = mock(ClientConfiguration.class);
    client = mock(Client.class);
    clientConfig.createClient();
    webTarget = mock(WebTarget.class);
    clientConfig.createWebResource(URI);
    response = mock(Response.class);
    invocationBuilder = mock(Invocation.Builder.class);
    statusType = mock(StatusType.class);
    when(client.target(URI)).thenReturn(webTarget);
    when(clientConfig.createWebResource(anyString())).thenReturn(webTarget);
    when(webTarget.path(anyString())).thenReturn(webTarget);
    when(webTarget.queryParam(anyString(), anyString())).thenReturn(webTarget);
    when(webTarget.register(RetrieveBillingResponseXMLReader.class)).thenReturn(webTarget);
    when(webTarget.request()).thenReturn(invocationBuilder);
    when(invocationBuilder.header(anyString(), Mockito.any())).thenReturn(invocationBuilder);
    when(invocationBuilder.accept(anyString())).thenReturn(invocationBuilder);
    when(invocationBuilder.get(Response.class)).thenReturn(response);
    when(response.readEntity(Mockito.any(Class.class))).thenReturn(baseModel);
    when(response.getStatusInfo()).thenReturn(statusType);
    when(statusType.getStatusCode()).thenReturn(status);
}
public ClientConfiguration getClientConfig() {
    return clientConfig;
}
}

我的JUnit测试。

 @Test
public void testRetrieveBillingJSONParseException() throws   EISClientException, Exception {
    RetrieveEnhancedBillingSummaryResponse entity = new RetrieveEnhancedBillingSummaryResponse();
    MockJerseyClient mockClient = new MockJerseyClient("mig", 200, "application/json", entity, CATEGORY.JSON);
    EISBillingClient client = new EISBillingClient(mockClient.getClientConfig(), "url");
    RetrieveBillingServiceRequest request = client.getRetrieveBillingRequest();
    request.setAccepts(ContentType.JSON);
    request.setParameters(client.getRetrieveBillingRequestParameters("HO123456789", "11302015"));
    boolean caughtException = false;
    try {
        @SuppressWarnings("unused")
        RetrieveBillingServiceResponse response = client.retrieveBilling(request);
    } catch (Exception ex) {
        if (ex instanceof EISClientException) {
            caughtException = true;
            assertEquals("Exception in processing the Retrieve Billing Call", ex.getMessage());
            assertTrue(ex.getCause() instanceof JsonParseException);
        } else {
            ex.printStackTrace();
            fail("Target exception other than JsonParseException.");
        }
    }
    assertTrue(caughtException);
 }

谢谢,

看起来您正在返回RetrieveEnhancedBillingSummaryResponse baseModel,而您的测试系统正在等待RetrieveBillingResponse。Mockito不会发现您正在使用错误的类型,但它稍后仍会失败。

注意,当你说:

when(response.readEntity(Mockito.any(Class.class))).thenReturn(baseModel);

您的意思是,无论readEntity中传递了什么类,都将返回baseModel。相反,您可能希望在那里进行类型检查,特别是如果您对多个调用使用相同的模拟response

when(response.readEntity(baseModel.getClass()).thenReturn(baseModel);

当且仅当对readEntity的调用试图读取baseModel类的对象时,这将返回baseModel

最新更新