Robolectric测试报java.lang.NoClassDefFoundError,如何解决?
NoClassDefFoundError: org/robolectric/internal/ShadowExtractor的解决方案 问题背景
我配置了这些测试依赖:
testImplementation 'org.robolectric:shadows-play-services:3.4-rc2' testImplementation "org.robolectric:robolectric:3.6.1" testImplementation "com.google.android.gms:play-services-auth:$rootProject.ext.googlePlayServicesVersion" // the robolectric shadow bogusly needs this
并编写了测试基类:
import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GoogleApiAvailability; import org.junit.Before; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.gms.Shadows; import org.robolectric.shadows.gms.common.ShadowGoogleApiAvailability; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE, shadows = {ShadowGoogleApiAvailability.class}) public abstract class BaseTest { @Before public void setUp() { final ShadowGoogleApiAvailability shadowGoogleApiAvailability = Shadows.shadowOf(GoogleApiAvailability.getInstance()); final int expectedCode = ConnectionResult.SUCCESS; shadowGoogleApiAvailability.setIsGooglePlayServicesAvailable(expectedCode); } }
但运行测试时抛出异常:
java.lang.NoClassDefFoundError: org/robolectric/internal/ShadowExtractor
异常栈指向org.robolectric.shadows.gms.Shadows.shadowOf(Shadows.java:37)和BaseTest.setUp(BaseTest.java:19)。
问题原因
这个错误的核心是Robolectric核心库和shadows-play-services扩展库的版本不兼容。你用的Robolectric是3.6.1版本,而shadows-play-services是3.4-rc2版本——Robolectric在3.5+版本中重构了内部的Shadow提取逻辑,移除/重命名了旧的org.robolectric.internal.ShadowExtractor类,但旧版本的shadows-play-services还在依赖这个已不存在的类,所以导致了找不到类的错误。
修复步骤
统一依赖版本
把shadows-play-services的版本升级到和Robolectric核心库一致的3.6.1,确保两者API兼容:testImplementation 'org.robolectric:shadows-play-services:3.6.1' testImplementation "org.robolectric:robolectric:3.6.1" testImplementation "com.google.android.gms:play-services-auth:$rootProject.ext.googlePlayServicesVersion"排查依赖冲突
执行Gradle命令查看依赖树,确认没有旧版本的Robolectric或shadows库被间接引入:./gradlew dependencies如果发现有冲突的旧版本,可以用
exclude语法排除,比如:testImplementation('org.robolectric:shadows-play-services:3.6.1') { exclude group: 'org.robolectric', module: 'robolectric' }验证代码兼容性
版本统一后,你原来的基类代码不需要修改就能正常运行。如果后续遇到其他Shadow获取的问题,也可以尝试改用Robolectric 3.5+推荐的Shadow.extract()方法(不过这个场景下版本匹配就足够解决问题了)。
完成上述修改后,重新同步Gradle项目并运行测试,NoClassDefFoundError的问题应该就能解决了。
内容的提问来源于stack exchange,提问作者Gabor

