在Gradle中添加依赖项

3

我不知道为什么我的依赖项没有起作用。 这是我的配置:

ext {
   junitVersion = "4.11"

   libs = [
           junit : dependencies.create("junit:junit:4.11")
   ]
}

configure(subprojects) { subproject ->
    dependencies {
        testCompile(libs.junit)
    }
}

我收到了错误信息:
* What went wrong:
A problem occurred evaluating root project 'unit590'.
> Could not find method testCompile() for arguments [DefaultExternalModuleDependency{group='junit', name='junit', version='4.11', configuration='default'}] on org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@785c1069.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

感谢您的帮助。
2个回答

9
testCompile配置由java插件声明。因此,在向testCompile添加依赖项之前,您需要将apply plugin: "java"应用于subprojects
PS:可以像马特的答案所示那样简化libs的声明。configure(subprojects) { ... }可以简化为subprojects { ... }

非常感谢,我是Gradle的新手用户 :) - Łukasz Woźniczka

1
请尝试使用这个替代方案。
ext {
   junitVersion = "4.11"

   libs = [
           junit : "junit:junit:${junitVersion}"
   ]
}

configure(subprojects) { subproject ->
    dependencies {
        testCompile libs.junit
    }
}

dependencies DSL依赖于Groovy的methodMissing实现,在我手头的Gradle版本中,看起来是这样的。

public Object methodMissing(String name, Object args) {
    Configuration configuration = configurationContainer.findByName(name)
    if (configuration == null) {
        if (!getMetaClass().respondsTo(this, name, args.size())) {
            throw new MissingMethodException(name, this.getClass(), args);
        }
    }

    Object[] normalizedArgs = GUtil.collectionize(args)
    if (normalizedArgs.length == 2 && normalizedArgs[1] instanceof Closure) {
        return doAdd(configuration, normalizedArgs[0], (Closure) normalizedArgs[1])
    } else if (normalizedArgs.length == 1) {
        return doAdd(configuration, normalizedArgs[0], (Closure) null)
    }
    normalizedArgs.each {notation ->
        doAdd(configuration, notation, null)
    }
    return null;
}

这将被称为dependencies{}内每个语句的调用,并提供了一个简洁易懂的DSL代替对add/create等方法的调用。

我的版本将通过测试编译作为第一个字符串参数和GAV符号字符串作为第二个参数传递,因此它将像往常一样进入doAdd方法(字符串符号由相关的NotationParser(在这种情况下是org.gradle.api.internal.notations.DependencyStringNotationParser)解析)。

您当前的使用方式让它认为您正在寻求调用名为DependencyHandler#testCompile的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接