我正在进行单元测试,其中包括使用XStream解析器解析数据.我使用Mockito来模拟上下文.但测试用例失败并出现错误日志:
java.lang.RuntimeException: Method newInstance in org.xmlpull.v1.XmlPullParserFactory not mocked. See http://g.co/androidstudio/not-mocked for details.
at org.xmlpull.v1.XmlPullParserFactory.newInstance(XmlPullParserFactory.java)
at com.thoughtworks.xstream.io.xml.XppDriver.createParser(XppDriver.java:57)
at com.thoughtworks.xstream.io.xml.AbstractXppDriver.createReader(AbstractXppDriver.java:54)
at com.thoughtworks.xstream.io.xml.AbstractXppDriver.createReader(AbstractXppDriver.java:65)
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:1049)
at com.att.apis.metadata.MetadataHandler.execute(MetadataHandler.java:38)
at com.att.apis.services.ServerOperations.executePostOperation(ServerOperations.java:20)
at com.att.framework.helper.request.MetadataAPIHandler.executeAPIRequest(MetadataAPIHandler.java:58)
at com.att.framework.helper.request.MetadataAPIHandlerMokitoTest.executeAPIRequest(MetadataAPIHandlerMokitoTest.java:57)
错误发生在以下代码块中的“response =(MetadataResponse)xs.fromXML(iStream);”行
InputStream iStream = responseData.getInputStream();
XStream xs = new XStream();
xs.autodetectAnnotations(true);
xs.alias("helloa", A.class);
xs.alias("hellob", B.class);
xs.alias("helloc",C.class);
response = (MetadataResponse)xs.fromXML(iStream);
根据Android: XmlPullParserFactory.newInstance() creating a null factory的回答,我补充道
testOptions {
unitTests.returnDefaultValues = true
}
在build.gradle中.
更新后发生NullPointer异常时发生以下日志.
java.lang.NullPointerException
at com.thoughtworks.xstream.io.xml.XppDriver.createParser(XppDriver.java:59)
at com.thoughtworks.xstream.io.xml.AbstractXppDriver.createReader(AbstractXppDriver.java:54)
at com.thoughtworks.xstream.io.xml.AbstractXppDriver.createReader(AbstractXppDriver.java:65)
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:1049)
at com.att.apis.metadata.MetadataHandler.execute(MetadataHandler.java:38)
at com.att.apis.services.ServerOperations.executePostOperation(ServerOperations.java:20)
at com.att.framework.helper.request.MetadataAPIHandler.executeAPIRequest(MetadataAPIHandler.java:58)
at com.att.framework.helper.request.MetadataAPIHandlerMokitoTest.executeAPIRequest(MetadataAPIHandlerMokitoTest.java:57)
任何人都可以帮我解决问题
解决方法:
XmlPullParserFactory来自Android平台,因此无法在单元测试中进行模拟,因为它们是使用您计算机上安装的Java VM执行的.
您可能想要使用Robolectric框架,它允许单元测试来调用Android平台(它几乎淹没了整个平台中的所有内容)