How I learned to stop worrying and love the unit tests

17
Dr. Droid or: How I Learned to Stop Worrying and Love the Unit-tests Android, Units, Robolectric

Transcript of How I learned to stop worrying and love the unit tests

Dr. Droid or: How I Learned to Stop Worrying

and Love the Unit-testsAndroid, Units, Robolectric

Who am I?

● Michael Pustovit

● Work at Stanfy as Android Engineer

● Moderator of KyivAndroidDevClub

Our plan

1. What is unit-test

2. Unit testing in Android

3. Robolectric: why?

4. A bit of live-coding

Unit tests

Unit testing is a software testing method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine whether they are fit for use.Wikipedia

We use them in TDD

● TDD - test-driven development

● Software development process that relies on the repetition of a very short development cycle

Unit testing in Android

● Android initially has tools for unit testing

● Instrumentation tests (are executed on real

device or simulator)

● Really slow, too slow for TDD

Why can’t we run tests on JVM?

● Android controls our program

● Our program use classes from Android OS

● Android = framework classes + set of services

● Execute all services on desktop = emulator

But we can compile our program

● It’s because we have android.jar

● So we can run tests on JVM but...

● But android.jar is stub○ any method will throws RuntimeException(“Stub!”)○ not really… newest android.jar will throw

RuntimeException(“Method not mocked”)

We’ll mock them all!

● We can mock android.jar○ android-gradle-plugin 1.1.0+ supports mock android.

jar● But there should be tons of mocks

Actually it’s what Robolectric does● Robolectric simulates Android

framework classes● Actually it executes Android

classes (or simulate theirs behaviour) on JVM

● As result, you can run your tests on JVM

But how?!

● Robolectric intercepts class loading (javassist)

● For classes which can’t be executed on JVM Robolectric creates “shadows”

Shadows

● Shadow mimics real class behaviour

● You know about shadow state (handy for

tests)

● You can create custom shadows

Lets code!

https://github.com/lampapos/UnitTestSample

Libs for testing

● AssertJ

● AssertJ Android

● Mockito

Cool assertions “assertThat().something()...”

Mocking framework