Skip to content

Instantly share code, notes, and snippets.

@fkirc
Created March 26, 2020 22:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fkirc/08bd2f0ee6f8fd338a257481e5f618ee to your computer and use it in GitHub Desktop.
Save fkirc/08bd2f0ee6f8fd338a257481e5f618ee to your computer and use it in GitHub Desktop.
Make Android UI tests fail if an error gets logged to Timber
import android.util.Log
import androidx.test.espresso.Espresso
import org.junit.Assert
import timber.log.Timber
/**
* During UI tests, we want to fail the test immediately if any "non-fatal error" happens.
* The purpose of non-fatal errors is to inform as about production failures without crashing the entire app.
*/
object NonFatalAbortTree: Timber.Tree() {
override fun log(priority: Int, tag: String?, message: String, throwable: Throwable?) {
if (priority == Log.ERROR || priority == Log.ASSERT) {
abortTest(message=message, throwable = throwable)
}
}
private fun abortTest(message: String, throwable: Throwable?) {
if (disabled) {
return
}
Assert.fail(message)
throw IllegalStateException(message, throwable)
}
fun plantInTimber() {
Timber.plant(this)
}
private var disabled = false
fun runWithoutAborts(waitIdle: Boolean = true, runnable: () -> Unit) {
disabled = true
runnable()
if (waitIdle) {
Espresso.onIdle()
}
disabled = false
}
}
@fkirc
Copy link
Author

fkirc commented Mar 26, 2020

Usage:
Call NonFatalAbortTree.plantInTimber() somewhere in the setup code of the UI tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment