使用 Mockito 模拟泛型类



我有下面的泛型类,我正在使用 mockito 模拟它的方法 xmlToObject((,如下所示,但是,该类没有被嘲笑,调用正在进入方法主体。其次,如果调用要到方法主体,则输入参数字符串为 null。

// Mocking code:
String responseXml = "<myDetails><resultCode>000000</resultCode><resultDesc>done</resultDesc></myDetails>";
MyDetails resp = new MyDetails();
byte b1 = 0; // 1 byte.
resp.setResultCode(b1);
resp.setResultDesc("");
JAXBElement<MyDetails> queryMyDetailsJaxb=  new JAXBElement( 
new QName(MyDetails.class.getSimpleName()), MyDetails.class, resp);
XMLToObject<MyDetails> mockFoo = (XMLToObject<MyDetails>) mock(XMLToObject.class);
when(mockFoo.xmlToObject(responseXml ,MyDetails.class)).thenReturn(queryMyDetailsJaxb);
Actual Class:
public class XMLToObject<T> {
public JAXBElement<T> xmlToObject(String xmlString, Class<T> t){
System.out.println("Inside xmlToObject with xmlString: "+xmlString+", object.class: "+t);
JAXBElement<T> resultObject = null;
StreamSource streamSource = null;
Unmarshaller jaxbUnmarshaller = null;
JAXBContext jaxbContext = null; 
try {  
jaxbContext = JAXBContext.newInstance(t);  
jaxbUnmarshaller = jaxbContext.createUnmarshaller();
streamSource = new StreamSource(new StringReader(xmlString));
resultObject = (JAXBElement<T>) jaxbUnmarshaller.unmarshal(streamSource, t);
System.out.println("resultObject.class: "+resultObject.getClass());
return resultObject;
} catch (JAXBException e) {  
System.out.println("xmlToObject: "+e.printStackTrace());
}
return resultObject;  
}   
}

Please guide me how can i mock my class and return the custom made object while mocking.

尝试更改

when(mockFoo.xmlToObject(responseXml ,MyDetails.class)).thenReturn(queryMyDetailsJaxb);

when(mockFoo.xmlToObject(anyString(),any(Class.class))).thenReturn(queryMyDetailsJaxb);

相关内容

  • 没有找到相关文章

最新更新