Gradle错误:'error: package com.google.common.collect does not exist'。

4

我正在遵循一个小测试脚本,并提供第一段代码使其变为绿色。代码是Java,测试是使用Java的Gradle。Java版本为“1.8.0_60”,在Mac OSX“El Capitan”上运行。 Gradle的版本为2.8。

在使用gradle build后,显示以下错误:

$ gradle build
:compileJava
/Users/rsalazar/exercism/java/etl/src/main/java/Etl.java:1: error: package  com.google.common.collect does not exist
import com.google.common.collect.ImmutableMap;
                            ^
/Users/rsalazar/exercism/java/etl/src/main/java/Etl.java:9: error: cannot find symbol
    return ImmutableMap.of("a", 1);
           ^
  symbol:   variable ImmutableMap
  location: class Etl
2 errors
:compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Compilation failed; see the compiler error output for details.

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

BUILD FAILED

Total time: 2.597 secs

这里是build.gradle文件:

apply plugin: "java"
apply plugin: "eclipse"
apply plugin: "idea"

repositories {
  mavenCentral()
}

dependencies {
  testCompile "junit:junit:4.10"
  testCompile "org.easytesting:fest-assert-core:2.0M10"
  testCompile "com.google.guava:guava:16+"
}

这里是测试: (EtlTest.java)。
import com.google.common.collect.ImmutableMap;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static org.fest.assertions.api.Assertions.assertThat;

public class EtlTest {
  private final Etl etl = new Etl();

  @Test
  public void testTransformOneValue() {
    Map<Integer, List<String>> old = ImmutableMap.of(1, Arrays.asList("A"));
    Map<String, Integer> expected = ImmutableMap.of("a", 1);

    assertThat(etl.transform(old)).isEqualTo(expected);
  }
}

这里是被测试的代码:(Etl.java)。
import com.google.common.collect.ImmutableMap;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Etl {
  public Map<String, Integer> transform(Map <Integer, List<String>> from) {
    return ImmutableMap.of("a", 1);
  }
}

我不是在寻求测试通过的帮助。只需要帮忙让测试与Gradle编译相兼容。很抱歉,在编译时遇到了错误信息而卡住了,我在网上找不到任何帮助。非常感谢!

1个回答

10

由于您需要在源代码中(不仅是测试源文件)编译ImmutableMap,因此需要更改此行:

testCompile "com.google.guava:guava:16+"

变成这样:

compile "com.google.guava:guava:16+"

它将在编译时使番石榴在源代码中可用,从而解决问题。


非常感谢!它完美地运行了。我需要阅读更多关于gradle的内容,但它看起来很适合开始学习Java和Groovy。再次感谢。我建议每个人都跟随'exercism' Java分支,并为'groovy'分支提供支持,因为它已经萎靡不振了。 - rafa2000
我试图给你一些声望值,但似乎在做到那一步之前,我必须先达到第13级。 - rafa2000
1
我遇到了相同的问题,但是是在使用Maven时。你的回复帮助我意识到了问题所在。谢谢。 - Òscar Raya

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