aowen
aowen

Reputation: 47

How to share dependencies between sibling multi-projects in gradle?

My project uses Gradle's multi-project system. Most of my projects include the "lemur-common" library like this

dependencies {
    compile project(":lemur-common")
}

"lemur-common" also has a unit test directory, which has a somewhat complicated dependency statement.

dependencies {
    testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.3.9.RELEASE'
    testCompile group: 'org.mockito', name: 'mockito-inline', version: '3.5.6'
    constraints {
        implementation('org.mockito:mockito-core:3.5.6') {
            because 'Fixes illegal reflective access warning'
        }
    }
}

Now, all of my other projects need to have this same line, since they're all using spring-boot-starter-test. I've done quite a bit of fiddling, trying to express something like "project-a's testCompile should have the same dependencies as lemur-common" but I haven't gotten it to work.

Is it possible to express this in Gradle? Does anyone know how?

Upvotes: 1

Views: 1696

Answers (1)

Randi Trigger
Randi Trigger

Reputation: 68

You'll want to create a custom Gradle plugin.

As a sibling of all your project dirs, create a buildSrc directory, which itself will have a Gradle file (it needs to be built like everything else). Make gradle file under src, which will be your plugin. Put all of the shared gradle code (the dependencies block you posted) in that file. For example:

- buildSrc
   |── build.gradle
   |── settings.gradle
   |── src
       |── main
          |── groovy
              |── unit-test-dependencies.gradle

Then, in the build.gradle of lemur-common, projectA, and etc. add this line

plugins {
    id 'unit-test-dependencies'
}

That should do it. Gradle's documentation for this feature is here: https://docs.gradle.org/current/samples/sample_convention_plugins.html

Upvotes: 1

Related Questions