Excluding jars via Gradle in unit tests

馋奶兔 提交于 2021-02-11 04:53:40

问题


I'm including some locally-built libs from another project by using fileTree():

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    ...
}

For unit testing, I want to use my own mock classes instead of those jars. How can I have the testImplementation configure not use those jar files and instead use similarly-named classes out of my source hierarchy?


回答1:


By default the testImplementation configuration extends from the implementation one so every dependency added to implementation will be present in testImplementation.

So the best option is to declare these specific dependencies into a different configuration, let's call it extraDeps, which you then add to the compileClasspath configuration:

configurations {
    extraDeps
    compileClasspath.extendsFrom(extraDeps)
}

dependencies {
    extraDeps fileTree(dir: 'libs', include: ['*.jar'])
}

This gives you the following advantages:

  • Shared dependencies between compile and test can still be in implementation
  • Special dependencies are identified clearly as they are in their own configuration
  • Compile classpath sees all it needs
  • Test classpath does not see the special jars



回答2:


In my case I needed to include aar for implementation and replace it with jar for unit tests. Gradle can't exclude jar files, so I found different solution.

Let's say I have Android project in folder MyProject. So there must be files MyProject/build.gradle and MyProject/app/build.gradle. I put <my-dependency>.aar file and <my-test-dependency>.jar files to MyProject/app/libs directory. Then I add this directory as local repository in MyProject/build.gradle file:

allprojects {
    repositories {
        ...
        flatDir {
            dirs 'libs'
        }
    }
}

Now I can include and exclude my aar by name:

configurations.testImplementation {
    exclude module: '<my-dependency>'
}

dependencies {
    implementation(name: '<my-dependency>', ext:'aar')
    
    testImplementation(name: '<my-test-dependency>', ext:'jar')
    // fileTree also should work, i.e.:
    // testImplementation fileTree(dir: 'libs', include: ['*.jar'])
}


来源:https://stackoverflow.com/questions/52787449/excluding-jars-via-gradle-in-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!