main

square/leakcanary

Last updated at: 29/12/2023 09:37

AndroidExtensionsTest.kt

TLDR

This file contains a single test class called AndroidExtensionsTest with a single test method called identityHashCode(). The test verifies whether the identity hash code of an instance matches the identity hash code obtained from a heap dump.

Methods

identityHashCode()

This method is a test method that verifies whether the identity hash code of an instance matches the identity hash code obtained from a heap dump. It first checks the Android SDK version using the assumeTrue() method from JUnit to ensure the test runs only on devices with a SDK version of 24 or higher. It then retrieves the string representation of the current instance using toString() and creates a new file to store a heap dump. The heap dump is created using the AndroidDebugHeapDumper.dumpHeap() method, passing in the heap dump file as the argument. The test then opens the heap graph of the heap dump file using openHeapGraph() and searches for the test class instance by name. It obtains the instance's identity hash code in hexadecimal format using the hexIdentityHashCode property and compares it to the expected value, which is the string representation of the test class name concatenated with the obtained identity hash code. The test passes if the two values are equal.

Classes

Class 1: AndroidExtensionsTest

This class is a test class that contains a single test method called identityHashCode(). The test verifies whether the identity hash code of an instance matches the identity hash code obtained from a heap dump.

package leakcanary

import android.os.Build.VERSION.SDK_INT
import org.assertj.core.api.Assertions.assertThat
import org.junit.Assume.assumeTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import shark.HprofHeapGraph.Companion.openHeapGraph
import shark.hexIdentityHashCode

class AndroidExtensionsTest {

  @get:Rule
  var testFolder = TemporaryFolder()

  @Test fun identityHashCode() {
    assumeTrue("SDK_INT is $SDK_INT, shadow\$_monitor_ was introduced in 21", SDK_INT >= 24)

    // leakcanary.AndroidExtensionsTest@c559955
    val thisToString = toString()

    val heapDumpFile = testFolder.newFile()
    AndroidDebugHeapDumper.dumpHeap(heapDumpFile)

    val testClassName = this::class.java.name

    val identityHashCodeFromDump = heapDumpFile.openHeapGraph().use { graph ->
      val testClass = graph.findClassByName(testClassName)!!
      val testInstance = testClass.instances.single()
      testInstance.hexIdentityHashCode
    }

    assertThat("$testClassName@$identityHashCodeFromDump").isEqualTo(thisToString)
  }
}