You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

引入LeakCanary后因JUnit类存在被禁用,求解决方法

解决LeakCanary因JUnit测试类存在被禁用的问题

问题原因

LeakCanary默认会扫描classpath,一旦检测到org.junit.Test这类测试类,就会自动禁用自身,避免在测试环境中运行干扰测试流程。

有效解决方案

方案1:自定义LeakCanary的测试类检测标识

你找到的资源配置代码,需要放在debug环境的资源目录下,具体操作:

  1. 在项目中创建路径:src/debug/res/values/(不存在则手动创建)
  2. 在该目录下新建XML文件(比如leak_canary_config.xml),粘贴以下代码:
<resources>
  <string name="leak_canary_test_class_name">assertk.Assert</string>
</resources>

该配置会告诉LeakCanary:仅当classpath中存在assertk.Assert类时才禁用自身。只要你的项目debug依赖里没有这个类,LeakCanary就会正常启用。

方案2:精准排除JUnit依赖

你之前的全局排除未生效,大概率是JUnit通过其他依赖间接引入的。可以先排查依赖树:

  • 执行命令查看debug依赖树:
./gradlew :app:dependencies --configuration debugImplementation

找到引入JUnit的具体依赖,然后针对性排除,比如:

// 假设是某第三方debug依赖引入了JUnit
debugImplementation('com.example:some-debug-lib:1.0.0') {
    exclude group: 'junit', module: 'junit'
}

如果是LeakCanary自身依赖的JUnit(可能性极低),也可以在其依赖中排除:

debugImplementation('com.squareup.leakcanary:leakcanary-android:2.12') {
    exclude group: 'junit', module: 'junit'
}

方案3:手动强制启用LeakCanary

如果上述方法都不生效,可以跳过LeakCanary的自动检测逻辑,手动在Application中初始化:

class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        // 跳过分析进程判断,避免干扰
        if (LeakCanary.isInAnalyzerProcess(this)) {
            return
        }
        // 手动安装LeakCanary,忽略测试类检测
        LeakCanary.enableDisplayLeakActivity(this)
        AppWatcher.manualInstall(this)
    }
}

注意:此方法适用于LeakCanary 2.x版本,不同版本API可能有差异,需对应调整。

内容的提问来源于stack exchange,提问作者Yağmur Şancı

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:25:47