- 确认是否已经正确添加了LeakCanary到项目中,包括相关依赖库和配置。
- 在build.gradle文件中添加以下代码:
android {
// ...
defaultConfig {
// ...
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" // 替换为你自己的InstrumentationRunner
}
testOptions {
unitTests {
includeAndroidResources = true
}
execution {
// add this line
listeners {
// optionally, enable FailTestOnLeakRunListener to automatically fail tests
// that leak memory. see https://square.github.io/leakcanary/fail-test-on-leak/
listener "com.squareup.leakcanary.FailTestOnLeakRunListener"
}
}
}
}
dependencies {
// ...
androidTestImplementation 'com.squareup.leakcanary:leakcanary-android-instrumentation:2.5'
androidTestUtil 'com.squareup.leakcanary:leakcanary-android-no-op:2.5' // required only in Android library modules
testImplementation 'junit:junit:4.13.2'
}
- 确认测试类引用正确的InstrumentationRunner,并尝试重新运行测试。