如何以编程方式将依赖项添加到Gradle配置?

Noe*_*Yap 7 gradle

我有以下代码:

static def getFamilyDependencies(ConfigurationContainer configurations) {
    def result = configurations.collect { configuration ->
        configuration.allDependencies.findAll { dependency ->
            dependency instanceof DefaultProjectDependency
        } collect { projectDependency ->
            projectDependency.dependencyProject.name
        }
    } flatten()

    result as Set
}
Run Code Online (Sandbox Code Playgroud)

我想测试一下.到目前为止,我有:

@Test
void shouldGetFamilyDependencies() {
    final Project project = ProjectBuilder.builder().build()

    final configurations = project.getConfigurations()

    configurations.create('configuration0')
    configurations.create('configuration1')

    configurations.each { configuration ->
        println "***************** ${configuration}"

        configuration.allDependencies.each {
            println "@@@@@@@@@@@@@@@@@ ${it}"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如何向配置添加依赖项?以下不起作用:

    final Project subproject = ProjectBuilder.builder().build()
    configurations.configuration0 {
        subproject
    }
    configurations.configuration1 {
        allDependencies {
            subproject
        }
    }
Run Code Online (Sandbox Code Playgroud)

Ren*_*hke 5

这应该可以解决问题:

configuration.getDependencies().add(dependenyMock);
Run Code Online (Sandbox Code Playgroud)


Max*_*Max 5

尝试这样做:

project.getDependencies().add('compile', project(':common-configuration'))

compile- 配置的名称
:common-configuration- 要添加的项目的名称(或任何其他依赖项)


Noe*_*Yap 4

@Test
void shouldGetFamilyDependenciesAcrossAllConfigurations() {
    final expected = ['subproject-0', 'subproject-1']

    final Project project = ProjectBuilder.builder().build()
    final configurations = project.getConfigurations()

    configurations.create('configuration-0')
    final Project subproject0 = ProjectBuilder.builder().withName(expected[0]).build()
    project.dependencies {
        delegate.'configuration-0'(subproject0)
    }

    configurations.create('configuration-1')
    final Project subproject1 = ProjectBuilder.builder().withName(expected[1]).build()
    project.dependencies {
        delegate.'configuration-1'(subproject1)
    }

    final actual = RestorePublishedArtifactTask.getFamilyDependencies(configurations)

    assertThat(actual, hasItems(expected.toArray(new String[expected.size()])))
}
Run Code Online (Sandbox Code Playgroud)