Search code examples
androidxml-parsingxmlpullparserjunit3

Android JUnit and parsing xml data - what to test


I am trying to get more experience on JUnit and its usage in Android. Referring to this official Android training Parsing XML data I wonder if anyone can provide with an example on how to test some of the used methods.

Particularly how would you test the methods included in the class StackOverflowXmlParser and the methods loadXmlFromNetwork() and downloadUrl() [class NetworkActivity.java]


Solution

  • The best advice I can give you on unit testing is to first really understand what a unit of test is. When I write tests, in particular Unit Tests, I make sure my unit of test is a single class. EVERYTHING ELSE is mocked, and my test makes sure every public method on the class does what it promises.

    That said, the methods you are asking about are EVIL UNTESTABLE CODE. It's a bit shocking to see code like this come from a Google engineer. My glancing guess is it's a front end web developer because the variables are all declared at the top of the method, Javascript style and initialization of every local variable that doesn't have a value to null suggests whoever wrote the example isn't very experienced with Java.

    You would have to significantly refactor the methods to get them into a testable state. For instance loadXmlFromNetwork presents an API that lies. It isn't "loading" xml from the network, it's also parsing it into a List<Entry> then after that is done, it does more by cramming data from these entries into an HTML formatted String and then returns that.

    The first problem with just this method alone is that it's creating objects inside of itself, instead of asking for what it needs. This presents a problem for testing because you can't mock these objects to test the logic. In a test you wouldn't want to have to make a network dependency, so you'd want to mock the HttpURLConnection and mock the behavior to exercise YOUR code.

    To point you in the right direction, watch this video from Google's lead testing evangelist:

    http://www.youtube.com/watch?v=wEhu57pih5w