我正在編寫一個JUnit
測試用例,其中我得到ClassCastException
。當請求對象設置實體時,我得到這個異常。 serviceRequest.setEntity((ResendDocumentsRequest)request);
如何解決使用Mockito的ClassCastException?
下的測試方法
public Object invokeService(String key, Object request) {
if(UiIntegrationKeyConstants.RESEND_DOCUMENTS.equals(key)) {
ResendDocumentsServiceResponse serviceResponse = null;
try {
ESignatureClient client = (ESignatureClient) AppContext.getBean("eSignatureRestClient");
ResendDocumentsServiceRequest serviceRequest = client.getResendDocumentsServiceRequest();
serviceRequest.setEntity((ResendDocumentsRequest)request);
serviceResponse = client.resendDocuments(serviceRequest);
} catch (ESignatureClientException e) {
log.error("Exception while retrieving documents Detail "+ e.getMessage());
}
return serviceResponse.getEntity();
}
}
JUnit測試用例
private ResendDocumentsServiceRequest resendDocumentsServiceRequest;
private ResendDocumentsServiceResponse resendDocumentsServiceResponse;
@SuppressWarnings("unchecked")
@Before
public void setUP() {
mockStatic(AppContext.class);
esignatureClient = mock(ESignatureClient.class);
resendDocumentsServiceRequest = mock(ResendDocumentsServiceRequest.class);
resendDocumentsServiceResponse = mock(ResendDocumentsServiceResponse.class);
}
@Test
public void testESignatureClientException() {
ESignatureServiceInvoker invoker = new ESignatureServiceInvoker();
PowerMockito.when(AppContext.getBean(eq("eSignatureRestClient"))).thenReturn(esignatureClient);
when(esignatureClient.getResendDocumentsServiceRequest()).thenReturn(resendDocumentsServiceRequest);
try {
doThrow(new ESignatureClientException()).when(esignatureClient).resendDocuments(resendDocumentsServiceRequest);
resendDocumentsServiceResponse = (ResendDocumentsServiceResponse) invoker.invokeService(UiIntegrationKeyConstants.RESEND_DOCUMENTS , resendDocumentsServiceRequest);
} catch (ESignatureClientException ex) {
assertNotNull(ex);
}
}
堆棧跟蹤:
java.lang.ClassCastException: com.whatever.ResendDocumentsServiceRequest$$EnhancerByMockitoWithCGLIB$$15a76565 cannot be cast to com.whatever.ResendDocumentsRequest
您可以告訴mockito模擬其他接口,請參閱https://stackoverflow.com/questions/1170708/is-it-possible-to-create-a-mock-object-that-implements-multiple-interfaces-with –
我很欣賞快速復出。有什麼我可以添加到答案也使它值得嗎? – GhostCat