Android Unit Test Handle Expected Exception (Kotlin)
March 7, 2019Solution 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
@JvmField
val expectedException = ExpectedException.none()
fun expectFirestorePermissionDenied() {
expectedException.expect(ExecutionException::class.java)
expectedException.expectCause(isA(FirebaseFirestoreException::class.java))
expectedException.expectMessage(StringContains("PERMISSION_DENIED"))
}
@Test
fun 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
@Test
fun 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:
- algo-trading
- algolia
- analytics
- android
- android-ktx
- android-permission
- android-studio
- apps-script
- bash
- binance
- bootstrap
- bootstrapvue
- chartjs
- chrome
- cloud-functions
- coding-interview
- contentresolver
- coroutines
- crashlytics
- crypto
- css
- dagger2
- datastore
- datetime
- docker
- eslint
- firebase
- firebase-auth
- firebase-hosting
- firestore
- firestore-security-rules
- flask
- fontawesome
- fresco
- git
- github
- glide
- godot
- google-app-engine
- google-cloud-storage
- google-colab
- google-drive
- google-maps
- google-places
- google-play
- google-sheets
- gradle
- html
- hugo
- inkscape
- java
- java-time
- javascript
- jetpack-compose
- jetson-nano
- kotlin
- kotlin-serialization
- layout
- lets-encrypt
- lifecycle
- linux
- logging
- lubuntu
- markdown
- mate
- material-design
- matplotlib
- md5
- mongodb
- moshi
- mplfinance
- mysql
- navigation
- nginx
- nodejs
- npm
- nuxtjs
- nvm
- pandas
- payment
- pip
- pwa
- pyenv
- python
- recylerview
- regex
- room
- rxjava
- scoped-storage
- selenium
- social-media
- ssh
- ssl
- static-site-generator
- static-website-hosting
- sublime-text
- ubuntu
- unit-test
- uwsgi
- viewmodel
- viewpager2
- virtualbox
- vue-chartjs
- vue-cli
- vue-router
- vuejs
- vuelidate
- vuepress
- web-development
- web-hosting
- webpack
- windows
- workmanager
- wsl
- yarn