Android Instrumented Unit Test With Hamcrest (Testing Moshi Adapter)

May 14, 2018

There are 2 types on Unit Test in Android:

  • Local Unit Tests: run on your development machine (not Android devices), run faster, no dependencies on Android OS/services (require mock object). Identified as src/test in Android Studio.
  • Instrumented Unit Tests: run on Android device on emulator, run slower (compile & deploy), better simulation of production environment. Identified as src/androidTest in Android Studio.

Android Studio usually created ExampleInstrumentedTest in src/androidTest (app/java/{package_name}/androidTest)

Let’s create the following MoshiTest.

  • Put initialization code at @Before. It shall be run once per class before test begin.
  • Use @After to close objects when all test are completed.
  • Use @Test(expected = ...) when exception is expected
  • There are many ways to check for assertion. I use org.hamcrest.MatcherAssert.assertThat, or you can use org.junit.Assert.assertEquals as well.
import org.hamcrest.CoreMatchers.`is` as Is

class MoshiTest {
    lateinit var moshi: Moshi
    lateinit var adapter: JsonAdapter<PhotoPin>

    fun init() {
        moshi = Moshi.Builder()
        adapter = moshi.adapter<PhotoPin>(

    fun destroy() {


    @Test(expected = EOFException::class)
    fun testEmptyJson() {
        var item = adapter.fromJson("")!!

        assertThat(item.location, Is(nullValue()))

    fun testLocationMissing() {
        var item = adapter.fromJson("""{}""")!!

        assertThat(item.location, Is(nullValue()))

    fun testLocationValue() {
        var item = adapter.fromJson("""{"geo":"1.0, 2"}""")!!

        assertThat(item.location, Is(notNullValue()))
        assertThat(item.location?.lat, Is(1.0))
        assertThat(item.location?.lng, Is(2.0))

To run the test, right click on MoshiTest and select run 'MoshiTest' (CTRL + SHIFT + F10).

Android Unit Test Run

Once completed, the result is shown in the Run tab.

Android Unit Test Result

NOTE: It is more logical to run the above Moshi test as Local Unit Tests since there is no Android system dependencies.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.