This is a mirror of official site: http://jasper-net.blogspot.com/

Android Dependency Injection and Testing Libraries

| Tuesday, June 7, 2011
Anything and everything that makes life easier to develop for Android should be looked into. There are a couple of libraries that make testing easier, increase the modularity of your code, and provide already created mock objects: 
  • RoboGuice - This is an adaption of Google’s dependency injection library but for Android
  • Robolectric -This is a testing framework/platform which works to remove the need for constant mocking of Android objects.  It also works with RoboGuice.
I can’t begin to thank the guy that first introduced me to dependency injection enough. Coming from a C++ world, where objects can’t describe themselves and there is no reflection unless the developer purposefully implements it himself, to a more modern language I often created my own static factories to simulate the @inject pattern. But why reinvent the wheel each and every time if an object can describe itself perfectly to the virtual machine?

If you’ve never seen Dependency Injection (DI) before look at the “simple example” RoboGuice provides on their webpage. At first glance it might seem like a fancy way to clean up the code so that maintainers could focus on just the specifics of the actions within each method. That is a side benefit (a really nice one at that) but only a side benefit. The example does not demonstrate the true power of such a framework in testing and asserting bug-free code.

Without DI in your code base
Let’s take a look at a contrived example of what sort of pain points DI can help conquer and alleviate. Suppose that I have a method which needs some sort of widget that takes user input. How can I test such a method without requiring someone to step through a script (as in written instructions) wherein they manually enter all the different combinations which could result in a real world scenario? That’s expensive and time consuming. I’m not even going to mention the human factor for mistakes (like skipping a test by accident). Oops, I just did (see? So easy to make mistakes!)

Read more: Java code geeks

Posted via email from Jasper-net

0 comments: