skip to content

With LeakCanary, how do you make Android instrumentation tests fail on memory leaks, and why does the rule's position in a RuleChain matter?

level: seniorimportance: should knowfreq 32%

answer

  1. a separate androidTest artifact
  2. an assertion you call, or a rule
  3. runs only after the test passes
  4. before or after the activity is destroyed

basics

~20 s

Add leakcanary-android-instrumentation as an androidTestImplementation dependency and use the DetectLeaksAfterTestSuccess rule or call LeakAssertions.assertNoLeaks(). Placed outside the activity rule it catches activity leaks; inside, it catches fragment leaks that vanish once the activity is destroyed.

solid answer

~40 s

The debug `leakcanary-android` artifact disables heap dumping when it finds JUnit on the classpath, so tests use `leakcanary-android-instrumentation` instead. Calling `LeakAssertions.assertNoLeaks()` from the test thread waits out the watch delay for any watched objects, dumps and analyzes the heap if some are retained, and throws `NoLeakAssertionFailedError` when it finds application leaks; library leaks are only logged. The `DetectLeaksAfterTestSuccess` rule calls it after each test that passed, so a failing test is not also reported as a leak. Position matters because `ActivityScenarioRule` finishes the activity during teardown: a leak rule **outside** it runs after the activity is destroyed and catches leaked activities, while one **inside** runs before and catches fragment leaks that go away with the activity. `detectLeaksAfterTestSuccessWrapping()` installs both. `@SkipLeakDetection("reason")` mutes a known leak per test or per tag.

code

kotlin · 29 lines
kotlin
import androidx.test.ext.junit.rules.ActivityScenarioRule
import leakcanary.DetectLeaksAfterTestSuccess
import leakcanary.LeakAssertions
import leakcanary.SkipLeakDetection
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain

class ArticleScreenTest {
    @get:Rule
    val rules: RuleChain = RuleChain
        // Outer: checks after the activity is destroyed (activity leaks).
        .outerRule(DetectLeaksAfterTestSuccess(tag = "AfterActivityDestroyed"))
        .around(ActivityScenarioRule(ArticleActivity::class.java))
        // Inner: checks before it is destroyed (fragment and view leaks).
        .around(DetectLeaksAfterTestSuccess(tag = "BeforeActivityDestroyed"))

    @Test
    fun rotateArticleScreen() {
        // ... rotate the screen and interact ...
        LeakAssertions.assertNoLeaks(tag = "AfterRotation")
    }

    @SkipLeakDetection("Vendor SDK leak, see issue #1234")
    @Test
    fun openVendorPaywall() {
        // ... no leak assertion runs in this test ...
    }
}

go deeper

for a junior

Know that leak checks in tests use a separate androidTest dependency and a rule or assertion, and that the normal debug LeakCanary does not fail tests.

for a middle

Explain what assertNoLeaks() does step by step and why only application leaks fail the test by default.

for a senior

Reason about rule order around ActivityScenarioRule, use the wrapping helper and tags, and use @SkipLeakDetection with a tracked reason.

for a principal

Decide where leak checks run in CI: which screen tests carry them, how the extra heap-dump time is budgeted, and who owns each skipped leak until it is fixed.

## Why tests need their own setup In a debug build LeakCanary watches objects continuously, freezes the VM to dump the heap once enough objects are retained, analyzes in the background and reports through notifications. None of that suits a test run: nobody reads the notifications and nothing fails. So when `org.junit.Test` is on the classpath, the debug artifact disables heap dumping and analysis by itself. The class it looks for is configurable through the `leak_canary_test_class_name` string resource, for apps that ship JUnit in their debug classpath. Leak checks in tests come from a dedicated artifact: ```kotlin androidTestImplementation("com.squareup.leakcanary:leakcanary-android-instrumentation:2.14") ``` It arrived in LeakCanary 2.8 as `LeakAssertions` and the `DetectLeaksAfterTestSuccess` rule, replacing `FailTestOnLeakRunListener`, which depended on `androidx.test` internals and was removed in 2.9.1. ## The assertion `LeakAssertions.assertNoLeaks(tag)` checks the heap at that moment: 1. If no watched object is still in memory, it returns at once. Otherwise it waits for the main thread to go idle, forces garbage collections and waits out the watch delay; if nothing is retained by then, the test continues. 2. Otherwise it dumps the heap and analyzes it with the same Shark analyzer the debug app uses. 3. The result goes to a `HeapAnalysisReporter`. The default, `NoLeakAssertionFailedError.throwOnApplicationLeaks()`, throws `NoLeakAssertionFailedError` (an `AssertionError`) with the full leak trace if there is at least one **application leak**, and only logs library leaks. It must not run on the main thread, and it can block for a long time while dumping and analyzing, so call it from the test method's instrumentation thread. The project docs spell the method `assertNoLeak()` in places; the 2.14 API is `assertNoLeaks()`. ## The rule `DetectLeaksAfterTestSuccess(tag)` is a JUnit `TestRule` that: - runs the test, and only if it passed, calls `LeakAssertions.assertNoLeaks(tag)`; - clears all watched objects afterwards in a `finally` block, so leftovers from one test are not blamed on the next; - applies `TestDescriptionHolder`, which `@SkipLeakDetection` needs to see which test is running. You can still call `assertNoLeaks()` inside a test as many times as you like; with the rule, each test gets one extra check at the end. ## Why the position in a RuleChain matters `ActivityScenarioRule` launches the activity before the test and finishes it during teardown. JUnit rules nest, so where the leak rule sits decides what has been torn down when it checks: | Arrangement | Runs | Catches | Misses | |---|---|---|---| | Leak rule outside `ActivityScenarioRule` | after the activity is destroyed | leaked activities | fragment leaks that disappear with the activity | | Leak rule inside `ActivityScenarioRule` | while the activity still exists | fragments and views already destroyed | the activity itself | | Both, via `detectLeaksAfterTestSuccessWrapping(tag)` | before and after | both kinds | nothing from this list | The helper adds the rule twice around the rules you wrap, suffixing the tags with `Before` and `After`. ## Muting a known leak - `@SkipLeakDetection("See issue #1234")` on a test or class skips every leak assertion in it. - `@SkipLeakDetection("See issue #1234", "AfterActivitiesDestroyed")` skips only assertions with those tags. - The message is mandatory; treat each annotation as a ticket to close, not as a permanent exemption. ## Customizing the reporting `LeakAssertions` delegates to a global `DetectLeaksAssert`. Replace it with `DetectLeaksAssert.update(AndroidDetectLeaksAssert(heapAnalysisReporter = ...))` to, for example, upload every analysis to a dashboard and then delegate to `throwOnApplicationLeaks()` so the test still fails. The analysis result carries the assertion tag in its metadata. ## Practical notes - Each check that finds retained objects costs a heap dump and an analysis, which adds noticeable time to a suite; teams often run leak rules on a focused set of screen tests rather than on every test. - Instrumentation tests against an obfuscated build can crash because LeakCanary classes end up split across the test and app APKs; the docs point to a plugin that keeps the needed classes. - A leak check only sees objects that were watched; screens never opened by the test are not covered. ## Where to call the assertion The rule and a direct call answer different needs: - **The rule** gives every test in the class one check at teardown, with no code in the test body; it is the default for screen tests. - **A direct `assertNoLeaks(tag)` call** checks at a specific point, for example right after rotating the screen or after leaving a flow, when objects destroyed by that step should already be gone; the tag shows up in the failure and in the analysis metadata. - **Tags make skips precise**: a test can mute only the `After` check of a wrapped pair while keeping the `Before` one, so a known activity leak does not hide new fragment leaks. A failure message contains the full heap analysis result, including the leak trace and metadata such as the device's SDK level, so a CI log is enough to start fixing without reproducing the leak locally.

  • Why does DetectLeaksAfterTestSuccess skip the check when the test fails?
    A failing test often leaves objects half torn down, which can look like leaks. Running the analysis then would bury the real failure under a leak report and cost a heap dump for nothing. The rule only checks after a successful run, and clears the watched objects either way so the next test starts clean.
  • Why does the debug LeakCanary stay quiet during tests instead of failing them?
    The debug artifact reports through notifications, which a test cannot assert on, and freezing the VM for dumps at unpredictable moments would make tests flaky. So it disables dumping when it finds JUnit on the classpath, and the instrumentation artifact takes over with explicit assertions at known points.

  • The debug leakcanary-android dependency fails UI tests on leaks by itself
  • DetectLeaksAfterTestSuccess also checks for leaks after a failing test
  • assertNoLeaks() should be called on the main thread inside runOnUiThread
  • Where the leak rule sits in the RuleChain makes no difference
  • FailTestOnLeakRunListener is the current way to fail tests on leaks

Assumes LeakCanary 2.14; LeakAssertions and DetectLeaksAfterTestSuccess arrived in 2.8, replacing FailTestOnLeakRunListener, which was removed in 2.9.1.