如何使用ProGuard在生产构建中排除测试类?
优化Android测试场景的ProGuard配置建议
Hey there! Since your unit tests live in the test directory (local unit tests) and UI tests are in androidTest (instrumented tests), let's tweak your ProGuard setup to make sure obfuscation doesn't break your test execution. First, here's your existing config for reference:
-target 1.7 #目标版本 -dontusemixedcaseclassnames #指定混淆时不生成大小写混合的类名 -dontskipnonpubliclibraryclasses #指定不忽略非公共库类 -dontpreverify #指定不对处理后的类文件进行预验证。针对Android平台时无需开启此选项,可关闭以减少处理开销。
针对本地单元测试(test目录)的额外配置
Local unit tests run directly on your JVM, so we need to keep test classes and framework dependencies unobfuscated:
# Keep all test classes in your test directory -keep class com.yourpackage.test.** { *; } # Preserve common testing framework classes (adjust based on what you use) -keep class org.junit.** { *; } -keep class org.mockito.** { *; }
针对插桩UI测试(androidTest目录)的额外配置
Instrumented tests run on a device/emulator, so we need to protect both your app's core classes and the test classes themselves:
# Keep all instrumented test classes -keep class com.yourpackage.androidTest.** { *; } # Keep your app's classes that are being tested (narrow this down if needed) -keep class com.yourpackage.yourmodule.** { *; } # Preserve UI testing framework classes -keep class androidx.test.espresso.** { *; } -keep class androidx.test.ext.junit.** { *; }
Quick Tips
- Don't forget to replace
com.yourpackagewith your actual app package name—this is crucial for the rules to work! - If you're using other testing tools like Robolectric, add corresponding
-keeprules for those libraries too. - For debugging, add
-printmapping mapping.txtto your config; this generates a mapping file that helps you trace any test failures caused by obfuscation.
内容的提问来源于stack exchange,提问作者Steve C
相关产品推荐
相关产品推荐

