Android Studio Unit Test Timber Log
First you need to create TestTree class which will keep track of timber logs. This class should be under test package.
Android Studio Unit Test Timber Log
First you need to create TestTree class which will keep track of timber logs. This class should be under test package.
import timber.log.Timber
class TestTree : Timber.Tree() {
val logs = mutableListOf<Log>()
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
logs.add(Log(priority = priority, tag = tag, message = message, t = t))
}
data class Log(val priority: Int, val tag: String?, val message: String, val t: Throwable?)
}
Now lets define our class to be tested and it’s test class.
class HomeViewModel(): ViewModel() {
fun logScreen(){
Timber.d("Home Screen")
}
}
Now define the test class under the test package.
class HomeViewModelTest(){
private lateinit var testTree: TestTree
private lateinit var underTest: HomeViewModel
// Here we set the variables and connect our testTree to Timber.
// When ever a log is sent by Timber will be stored inside our tree.
@Before
fun setUp() {
testTree = TestTree()
Timber.plant(testTree)
underTest = HomeViewModel()
}
@Test
fun testTimberLog(){
underTest.logScreen()
// Get the latest timber log.
val actual = testTree.logs.last()
// Prepare the expected log. This one should be same as the original function log.
val expected = TestTree.Log(
priority = Log.DEBUG,
message = "Home Screen",
tag = null,
t = null
)
// Check if the log was captured.
Assert.assertEquals(actual.message, expected.message)
}
} 메타데이터
- post_id
- 4ea38cbc468b
- slug
- android-studio-unit-test-timber-log-4ea38cbc468b
- url
- https://medium.com/@tahirabuzetoglu/android-studio-unit-test-timber-log-4ea38cbc468b
- canonical_url
- https://medium.com/@tahirabuzetoglu/android-studio-unit-test-timber-log-4ea38cbc468b
- author_url
- https://medium.com/@tahirabuzetoglu
- status
- ok
- fetched_at
- 2026-07-22 19:50:38