Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Android Unit Testing with Robolectric

Android Unit Testing with Robolectric

Using Robolectric to facilitate Android Unit Testing, presented in Singapore Android Developers meetup http://www.meetup.com/Singapore-Android-Developers/events/194790032/

Nguyen Truong Tho

July 30, 2014
Tweet

Other Decks in Programming

Transcript

  1. Why Android is hard to do unit testing  Many

    of classes, methods are final  Lack of interfaces  Non public constructors  Static methods
  2. Have you tried?  Google does not want to show

    you the ugly part: Method bodies are replaced by a RuntimeException
  3. What have we tried?  No tests. God blesses us

    for almost half a year  Painful manual testing  Reproducing same bugs again and AGAIN  New developers join with risk  Integration testing  Slow  Not reliable  No fun  Robolectric  FuN~ 
  4. Robolectric  Tests run in JVM, not in DavikVM 

    No dexing, packaging, installation process. No emulator or device needed  Run on JVM  Fast  Freedom  Can use reflection without worry about performance  Can use big libraries, large jar file: apache common, google libraries like truth, guava.  Fast debugging and possible hot code swapping  Test behavior not implementation
  5. Shadow objects  Shadows back android classes. i.e ShadowImageView backs

    the ImageView class (Robolectric creates and uses shadow object instead of the real object if possible, look here)  Record state for testing verification  Simplify behaviors Shadow RealObject
  6. View and resources loading  Robolectric parses layout files and

    build a tree of view objects with shadows  Robolectric also loads strings.xml, colors.xml …  Simulate runtime Android environment.
  7. Demo  Source code available at: https://github.com/nguyentruongtho/robomeetup  Writing Robolectric

    Junit test  Customize RobolectricTestRunner  TestLifecycleApplication  Robolectric & Dependency injection (Dagger)  Customize Robolectric for Maven, Git Submodule
  8. Question?  http://www.tradehero.mobi/Careers  Join us, boss robolectric will be

    watching you   Me  http://twitter.com/thontu  http://github.com/nguyentruongtho  http://linkedin.com/in/nguyentruongtho/  Resources  http://robolectric.org/  http://www.slideshare.net/tylerschultz/robolectric-android-unit- testing-framework