leakcanary-android-instrumentation / leakcanary / InstrumentationLeakDetector
class InstrumentationLeakDetector
InstrumentationLeakDetector can be used to detect memory leaks in instrumentation tests.
To use it, you need to add an instrumentation test listener (e.g. FailTestOnLeakRunListener) that will invoke detectLeaks.
LeakCanary provides FailTestOnLeakRunListener, but you can also implement your own RunListener and call detectLeaks directly if you need a more custom behavior (for instance running it only once per test suite).
All you need to do is add the following to the defaultConfig of your build.gradle:
testInstrumentationRunnerArgument "listener", "leakcanary.FailTestOnLeakRunListener"
Then you can run your instrumentation tests via Gradle as usually, and they will fail when a memory leak is detected:
./gradlew leakcanary-sample:connectedCheck
If instead you want to run UI tests via adb, add a listener execution argument to your command line for running the UI tests: -e listener leakcanary.FailTestOnLeakRunListener
. The full command line should look something like this:
adb shell am instrument \\ -w com.android.foo/android.support.test.runner.AndroidJUnitRunner \\ -e listener leakcanary.FailTestOnLeakRunListener
Instead of using the InstrumentationLeakDetector, one could simply enable LeakCanary in instrumentation tests.
This approach would have two disadvantages:
The approach taken here is to collect all objects to watch as you run the test, but not do any heap dump during the test. Then, at the end, if any of the watched objects is still in memory we dump the heap and perform a blocking analysis. There is only one heap dump performed, no matter the number of objects retained.
Name | Summary |
---|---|
Result | sealed class Result The result of calling detectLeaks, which is either NoAnalysis or AnalysisPerformed. |
Name | Summary |
---|---|
<init> | InstrumentationLeakDetector() InstrumentationLeakDetector can be used to detect memory leaks in instrumentation tests. |
Name | Summary |
---|---|
detectLeaks | fun detectLeaks(): InstrumentationLeakDetector.Result Looks for retained objects, triggers a heap dump if needed and performs an analysis. |
Name | Summary |
---|---|
updateConfig | fun ~~updateConfig~~(): Unit |