最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I exclude a dependency from the test classpath but keep it in the main code with Gradle? - Stack Overflow

programmeradmin3浏览0评论

I have a Gradle dependency defined like this:

dependencies {
    implementation("com.example:my-library:1.0.0")
}

However, I don't want this library to be included in the test classpath. How can I exclude it from tests while keeping it available for the main code? Thanks!

I have a Gradle dependency defined like this:

dependencies {
    implementation("com.example:my-library:1.0.0")
}

However, I don't want this library to be included in the test classpath. How can I exclude it from tests while keeping it available for the main code? Thanks!

Share Improve this question asked Mar 14 at 17:00 kikulikovkikulikov 2,5815 gold badges33 silver badges45 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Simply excluding a dependency from the test classpath does not appear to be possible. This is for two reasons:

  • The test classpaths inherits from the main classpaths, so each main dependency will be there by default; and
  • In Gradle non-transitive dependencies are not optional so it's only possible to substitute the unwanted dependency for another, instead of outright rejecting it.

To do this then I suggest doing a "substitution" for a module you are happy to have on the classpath, ie:

// and/or use testRuntimeClasspath depending what you want exactly
configurations.testCompileClasspath { 
    resolutionStrategy {
        dependencySubstitution {
            substitute(module("com.example:my-library"))
                .using(module("com.example:my-safe-library:1.0.0"))
        }
    }
}

As you'll be aware, you'll get a ClassNotFoundException if you try and run code from the main source that uses the excluded module and you've excluded the library from the test runtime classpath.

You probably know also this, but for completeness I should probably say that excluding a dependency in this way suggests that there is something in your setup that is not quite as recommended as such a "hack" should not be necessary; however I appreciate that sometimes a shortcut is needed to "get things working".

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论