【问题标题】:Different Gradle dependency for test than for compile测试的 Gradle 依赖项与编译的不同
【发布时间】:2018-08-23 13:52:53
【问题描述】:

我正面临 Android/Gradle 依赖系统的这个问题

  1. 我有一个相当复杂的 JAR 库,其中包含某些 API - 比如说 other.jar
  2. 这个 other.sdk 完全不受我的控制
  3. 此 other.sdk 仅适用于真机
  4. 我需要编写要在 Jenkins 上执行的 jUnit 测试(不连接任何真实手机)
  5. 因此我编写了另一个名为 say otherMock.jar 的 JAR 文件
  6. 此 otherMock.jar 与 other.jar 具有完全相同的 API

现在我需要在我的 build.gradle 文件中做这样的事情:

...

dependencies {
    ...
    testCompile files('libs/otherMock.jar')
    debugCompile files('libs/other.jar')
    releaseCompile files('libs/other.jar')
    ...
}

...

不幸的是,Gradle 似乎在我的测试版本中同时包含了 other.jar 和 otherMock.jar。

我确实明白,对于大多数构建(包括我以前的所有构建)来说,这是非常理想的行为。

但对于我的特殊情况,这是一个问题。

所以我需要(例如)这样的东西:

...
dependencies {
    if(<I failed to realize which condition to write here to learn it is going to be a test>) {
        testCompile ...
    } else {
        debugCompile ...
        releaseCompile ...
    }
}

或者更好:

...
dependencies {
    testCompile ...
    debugCompile ... {
        exclude <when test build - what to write here?>
    }
}
...

我尽我所能来了解如何配置 Gradle 来做我需要的,但我失败了:(

另一方面,我不敢相信 Gradle 不够灵活,无法实现这一目标。我希望这对我来说太难了:) ...

请不要给我建议:

  • 在运行测试时包装 other.jar 并注入模拟的变体(我知道这是可能的,但这是很多额外的工作,对我来说毫无意义)
  • 将真实手机连接到我的 Jenkins(我无法这样做,因为我无法物理访问 Jenkins 虚拟机 + 在真实设备上我根本无法控制模拟)
  • 应用其他模拟机制,如 mockito - 我也尝试过,但 other.jar 库没有遵循良好的设计原则,因此很难以标准方式模拟 - 我仍然没有尝试 powermock,但再次尝试没有任何意义如果我成功完成依赖项,我会尝试

【问题讨论】:

    标签: java android testing gradle dependencies


    【解决方案1】:

    您可以使用Gradle configurationsGradle test 定义自定义配置并将其从测试任务类路径中排除:

    configurations {
       other.extendsFrom compile //latter is parent for both debugCompile and releaseCompile
    }
    
    test {
       classpath -= configurations.other
    }
    
    
    dependencies {
       testCompile files('libs/otherMock.jar')
       other files('libs/other.jar')
    }
    

    【讨论】:

    • 不适用于我的 Android gradle 插件。缺少测试任务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2014-04-14
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多