Android Unit Test Handle Expected Exception (Kotlin)

Mar 7, 2019

Solution 1: expected

Great for simple cases.

@Test(expected = IndexOutOfBoundsException::class)fun testException() {    val items = listOf(1, 2, 3)    val value = items[10]}

Solution 2: ExpectedException Rule

Sometimes detecting an exception class is not sufficient, where I need to

  • Detect the exception which cause this exception
  • Check the message of the exception
@Rule@JvmFieldval expectedException = ExpectedException.none()    fun expectFirestorePermissionDenied() {    expectedException.expect(ExecutionException::class.java)    expectedException.expectCause(isA(FirebaseFirestoreException::class.java))    expectedException.expectMessage(StringContains("PERMISSION_DENIED"))}@Testfun createUserByPublic() {    val task = db.collection("users")        .document("test_create_user_public")        .set(mapOf("roles" to listOf("user")))    expectFirestorePermissionDenied()    Tasks.await(task, 10, TimeUnit.SECONDS)}    

Solution 3: Try Catch

@Testfun testExceptionWithTryCatch() {    try {        val items = listOf(1, 2, 3)        val value = items[10]        fail("IndexOutOfBoundsException expected")    } catch (e: IndexOutOfBoundsException) {        assertThat(e.message, StringContains("Invalid index"))    }}

References:

❤️ 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.