简体   繁体   中英

Test data sources in Android unit testing

I want to test parsing of data returned from server.

I thought I might create several test XML files and then feed them to the sax parser which uses my custom data handler (as in the application that I test).

But where should I put those test XMLs?

I tried with [project_root]/res/xml , but then I get the error:

android.content.res.Resources$NotFoundException: Resource ID #0x7f040000 type #0x1c is not valid at android.content.res.Resources.loadXmlResourceParser(Resources.java:1870) at android.content.res.Resources.getXml(Resources.java:779)

Does that mean that the xml is invalid, or that android couldn't find the XML file? (I use the same XML that comes from the server - copied it from the firebug's net panel and pasted into the file).

Can I somehow read that XML as a text file, since getContext().getResources().getXml(R.xml.test_response1) returns XmlResourceParser instead of String (which I'd prefer)?

Put you xmls in MyAppTest/assets , for example MyAppTest/assets/my.xml , and then read it using

InputStream myxml = getInstrumentation().getContext().getAssets().open("my.xml");

then you can invoke the parser with this stream.

Simply put the file in your current package (ie into a resource package) and use the class loader...

private InputStream getTestImage(String pathToFile) throws IOException
        {
            final ClassLoader loader = getClass().getClassLoader();
            assertNotNull(loader);
            final InputStream resourceAsStream = loader.getResourceAsStream(pathToFile);
            assertNotNull(resourceAsStream);
            return resourceAsStream;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM