Slide 1

Slide 1 text

Android unit testing with Robolectric Tho Nguyen Senior Android Developer @TradeHero

Slide 2

Slide 2 text

How does Junit work

Slide 3

Slide 3 text

Why Android is hard to do unit testing  Many of classes, methods are final  Lack of interfaces  Non public constructors  Static methods

Slide 4

Slide 4 text

Have you tried?  Google does not want to show you the ugly part: Method bodies are replaced by a RuntimeException

Slide 5

Slide 5 text

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~ 

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

Robolectric

Slide 8

Slide 8 text

How does Robolectric work  Shadow Objects  View and resources loading

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

Custom shadow implementation

Slide 11

Slide 11 text

Using custom shadow  Declaration  Usage

Slide 12

Slide 12 text

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.

Slide 13

Slide 13 text

Writing test  Specify that the test needs android instrument.

Slide 14

Slide 14 text

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

Slide 15

Slide 15 text

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