安卓Robolectric异常

9
我在使用Robolectric库时遇到了问题。我正在使用Robolectric编写单元测试,在本地可以正常工作,但是当我合并我的代码后,在远程的pipeline上会崩溃。
我使用的是'org.robolectric:robolectric:4.0.2'版本。只需在我的测试类中添加此行即会失败:@RunWith(RobolectricTestRunner.class) 异常为:

失败 org.apache.tools.ant.BuildException Caused by: org.apache.maven.artifact.resolver.MultipleArtifactsNotFoundException

3个回答

5

我遇到了相同的问题:Robolectric在本地运行正常,但一旦推送到Jenkins上,执行测试的gradle任务就会失败。

您可以使用-i -d标志执行gradle任务以运行测试,并查看更多的调试输出。

./gradlew -i -d test

对我来说,这表明Jenkins无法下载Robolectric的依赖项:

13:58:43  13:58:42.904 [DEBUG] [TestEventLogger] com.my.package.Test > my_test_case STANDARD_ERROR
13:58:43  13:58:42.904 [DEBUG] [TestEventLogger]     Downloading: org/robolectric/android-all/9-robolectric-4913185-2/android-all-9-robolectric-4913185-2.jar from repository sonatype at https://oss.sonatype.org/content/groups/public/

我可以通过告诉gradle在Jenkins上运行时使用我们公司的代理来解决这个问题。实现此目的的一种方法是将以下内容添加到gradle.properties中:

systemProp.http.proxyHost=http://proxy.host
systemProp.http.proxyPort=3128
systemProp.https.proxyHost=http://proxy.host
systemProp.https.proxyPort=3128

---- 编辑 ----

实际上,我发现了一个比配置代理更加简洁的解决方案:Robolectric提供了一种在运行时配置其使用的存储库的方法(请参见http://robolectric.org/configuring/)。通过这种方式,我能够告诉它使用我们公司的存储库。

android {
  testOptions {
    unitTests.all {
      systemProperty 'robolectric.dependency.repo.url', 'https://local-mirror/repo'
      systemProperty 'robolectric.dependency.repo.id', 'local'
    }
  }
}

是的,完全正确,这就是问题所在。您使用的 Robolectric 版本是多少? - Najoua Mahi
目前我正在使用 4.3-beta-1,但它也可以与 4.2 一起使用。此外,我已经切换到了 Androidx 测试依赖项,使用 testImplementation 'androidx.test:core:1.1.0' - Christian.D
好的,我也切换到了Androidx,但是我通过创建自定义的RobolectricTestRunner来修复了错误。我会为其他人发布我的答案。 - Najoua Mahi

3
在我的情况下,问题是(./gradlew -i -d testDebug打印出来的):
Caused by:
org.apache.maven.artifact.resolver.MultipleArtifactsNotFoundException: Missing:
----------
1) org.robolectric:android-all:jar:10-robolectric-5803371
...

Robolectric试图从远程仓库获取依赖项,但失败了。

根据输出,我已经:

  1. 手动从Maven仓库下载了org.robolectric:android-all:jar:10-robolectric-5803371 jar文件。
  2. 将其放置在/home/user/jars目录下。
  3. 在我的机器上安装了Maven:sudo apt install maven
  4. 将该jar文件与Robolectic关联:mvn install:install-file -DgroupId=org.robolectric -DartifactId=android-all -Dversion=10-robolectric-5803371 -Dpackaging=jar -Dfile=/home/user/jars/android-all-10-robolectric-5803371.jar

现在./gradlew testDebug可以正常工作了。

还可以查看Github上的问题,也许会有更多有用的信息供您参考。


0
正如@Christian.D所说,Robolectric试图从外部存储库下载依赖项,但我们需要它使用内部存储库。以下是修复方法:
1)创建自定义的RobolectricTestRunner:
public class CustomRobolectricRunner extends RobolectricTestRunner {

public CustomRobolectricRunner(Class<?> testClass) throws InitializationError {
    super(testClass);
}

static {
    RoboSettings.setMavenRepositoryId("my-nexus");
    RoboSettings.setMavenRepositoryUrl("your_custom_url");
}
}

2) 给你的测试类加注释:

@Config(manifest = Config.NONE)
@RunWith(CustomRobolectricRunner.class)

写代码愉快!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接