Created
August 15, 2020 21:06
-
-
Save adammagana/f2a6d56c00a619eb55c2db7cab6b2442 to your computer and use it in GitHub Desktop.
A means to preserve logging on Android without breaking simple unit tests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.util.Log | |
import kotlin.reflect.KClass | |
/** | |
* An interface meant to trivialize the mocking of Android's [Log] methods. | |
*/ | |
interface Logger { | |
fun v(message: String) | |
fun d(message: String) | |
fun i(message: String) | |
fun w(message: String) | |
fun e(message: String) | |
fun wtf(message: String) | |
} | |
/** | |
* Given a "tag" string, this function spits out an implementation of the [Logger] interface. | |
* Powered by the Android [Log] class. | |
*/ | |
fun getLogger(tag: String): Logger = object : Logger { | |
override fun v(message: String) { | |
Log.v(tag, message) | |
} | |
override fun d(message: String) { | |
Log.d(tag, message) | |
} | |
override fun i(message: String) { | |
Log.i(tag, message) | |
} | |
override fun w(message: String) { | |
Log.w(tag, message) | |
} | |
override fun e(message: String) { | |
Log.e(tag, message) | |
} | |
override fun wtf(message: String) { | |
Log.wtf(tag, message) | |
} | |
} | |
/** | |
* Given a class reference, this function spits out an implementation of the [Logger] interface. | |
* Powered by the Android [Log] class. | |
*/ | |
fun getLogger(classRef: KClass<out Any>): Logger { | |
return getLogger(classRef.simpleName ?: "AnonymousObject") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment