Android Instrumented Unit Test With Hamcrest (Testing Moshi Adapter)

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@RunWith(AndroidJUnit4::class)class MoshiTest {    lateinit var moshi: Moshi    lateinit var adapter: JsonAdapter<PhotoPin>    @Before    fun init() {        moshi = Moshi.Builder()            .add(LocationAdapter())            .add(KotlinJsonAdapterFactory())            .build()        adapter = moshi.adapter<PhotoPin>(    }    @After    fun destroy() {    }    @Test(expected = EOFException::class)    fun testEmptyJson() {        var item = adapter.fromJson("")!!        assertThat(item.location, Is(nullValue()))    }    @Test    fun testLocationMissing() {        var item = adapter.fromJson("""{}""")!!        assertThat(item.location, Is(nullValue()))    }    @Test    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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.