ObjectInspectorTest.kt
TLDR
This file contains a class called ObjectInspectorTest
that is used to test the object inspection functionality provided by the LeakCanary library. It includes a single test method which checks if a leak caused by a LifecycleRegistry
object is reported correctly.
Methods
setUp
This method is executed before each test case and is responsible for clearing the objectWatcher
in AppWatcher
.
tearDown
This method is executed after each test case and is responsible for clearing the objectWatcher
in AppWatcher
.
LifecycleRegistry_LeakingStatus_Is_Reported
This test method verifies that a leak caused by a LifecycleRegistry
object is reported correctly. It triggers the creation and destruction of an activity, adds an observer to its lifecycle, and then checks if the leaked LifecycleRegistry
object is correctly identified with its state labeled as "DESTROYED".
package leakcanary
import androidx.lifecycle.LifecycleObserver
import leakcanary.TestUtils.detectLeaks
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class ObjectInspectorTest : HasActivityTestRule<TestActivity> {
@get:Rule
override val activityRule = activityTestRule<TestActivity>(launchActivity = false)
@Before fun setUp() {
AppWatcher.objectWatcher.clearWatchedObjects()
}
@After fun tearDown() {
AppWatcher.objectWatcher.clearWatchedObjects()
}
@Test fun LifecycleRegistry_LeakingStatus_Is_Reported() {
triggersOnActivityCreated {
activityRule.launchActivity(null)
}
activity.lifecycle retained {
runOnMainSync {
val observer = object : LifecycleObserver {}
activity.lifecycle.addObserver(observer)
AppWatcher.objectWatcher.expectWeaklyReachable(observer, "observer")
}
triggersOnActivityDestroyed {
activityRule.finishActivity()
}
Thread.sleep(AppWatcher.retainedDelayMillis)
val heapAnalysis = detectLeaks()
val leaktrace = heapAnalysis.allLeaks.single().leakTraces.single()
val ref = leaktrace.referencePath.single { it.owningClassSimpleName == "LifecycleRegistry" }
val lifecycleRegistry = ref.originObject
assertThat(lifecycleRegistry.labels.single()).isEqualTo("mState = DESTROYED")
}
}
}