使用Mockito的ClassCastException

时间:2015-12-01 17:02:34

标签: java mockito

我正在使用Mockito编写一个JUnit测试用例来测试JSONParseException但我得到的是ClassCastException。好像peoblem在行

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

谢谢,

1 个答案:

答案 0 :(得分:2)

看起来你正在返回一个RetrieveEnhancedBillingSummaryResponse baseModel,你的系统正在等待一个RetrieveBillingResponse。 Mockito不会发现你错误地输入了错误的类型,但它以后仍会失败。

请注意,当你说:

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

您说,无论将哪个班级传入baseModel,都会返回readEntity。相反,您可能希望在那里进行类型检查,特别是如果您使用相同的模拟response进行多次调用:

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

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