0

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]

eeadev
  • 3,662
  • 8
  • 47
  • 100
  • 2
    yes, but sometimes is not you the person who decides the format file to parse and the purpose of this post is to boost someone's JUnit(onAndroid) learning in a common scenario. – eeadev Mar 10 '13 at 09:40

1 Answers1

2

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

Christopher Perry
  • 38,891
  • 43
  • 145
  • 187
  • sorry Christopher, it's not for being a google friend but, as I know, local variable in java must be initialized and your link (http://www.javapractices.com/topic/TopicAction.do?Id=14) is referring to java fields (initializing fields is redundant). – eeadev Mar 10 '13 at 11:18
  • 1
    Local variables shouldn't be declared/initialized until their point of use, unless you're trying to do something like trying to use their value outside a try/catch block. See [here](http://www.javapractices.com/topic/TopicAction.do?Id=126) – Christopher Perry Mar 10 '13 at 20:07