使用Mockito模拟通用类

时间:2018-05-30 10:22:28

标签: mockito

我有下面的泛型类,我使用mockito模拟它的方法xmlToObject(),但是,该类没有被模拟,并且调用正在方法体内。其次,如果调用是方法体,则输入参数字符串为空。

// 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.

1 个答案:

答案 0 :(得分:0)

尝试更改

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

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