main

square/leakcanary

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

AndroidDetectLeaksAssertTest.kt

TLDR

This file, AndroidDetectLeaksAssertTest.kt, is a test class that tests the functionality of the AndroidDetectLeaksAssert class in the LeakCanary library. It sets up and tears down the necessary dependencies before and after each test method. There is a single test method, detectsLeak(), which creates a Date object and checks if it is leaked using the assertLeak() method.

Classes

AndroidDetectLeaksAssertTest

This class is a test class that checks if the AndroidDetectLeaksAssert class in the LeakCanary library can detect leaks in instrumentation tests. It sets up and resets the watched objects list before and after each test. The class contains the following methods:

  • setUp(): This method is executed before each test. It clears the list of watched objects in the objectWatcher provided by the AppWatcher class.
  • tearDown(): This method is executed after each test. It clears the list of watched objects in the objectWatcher provided by the AppWatcher class.
  • detectsLeak(): This method is a test method that creates a Date object and checks if it is leaked using the assertLeak() method. The leaking property is set to the Date object, and then it is added to the objectWatcher with a weak reachability expectation. Finally, the assertLeak() method is called to check if the Date object is leaked.
package leakcanary

import leakcanary.TestUtils.assertLeak
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.util.Date

/**
 * Tests that the [AndroidDetectLeaksAssert] can detect leaks
 * in instrumentation tests
 */
class AndroidDetectLeaksAssertTest {

  @Before fun setUp() {
    AppWatcher.objectWatcher
      .clearWatchedObjects()
  }

  @After fun tearDown() {
    AppWatcher.objectWatcher
      .clearWatchedObjects()
  }

  @Test fun detectsLeak() {
    leaking = Date()
    val objectWatcher = AppWatcher.objectWatcher
    objectWatcher.expectWeaklyReachable(leaking, "This date should not live beyond the test")
    assertLeak(Date::class.java)
  }

  companion object {
    private lateinit var leaking: Any
  }
}