2017-03-08 58 views
8

我想實現一個簡單的JUnit測試的gradle使用並運行到以下問題,當我運行gradle testgradle這個compileJava錯誤:包org.junit不存在

:compileJava 
/Users/wogsland/Projects/gradling/src/test/CalculatorTest.java:1: error: package org.junit does not exist 
import static org.junit.Assert.assertEquals; 
        ^
/Users/wogsland/Projects/gradling/src/test/CalculatorTest.java:1: error: static import only from classes and interfaces 
import static org.junit.Assert.assertEquals; 
^ 
/Users/wogsland/Projects/gradling/src/test/CalculatorTest.java:2: error: package org.junit does not exist 
import org.junit.Test; 
       ^
/Users/wogsland/Projects/gradling/src/test/CalculatorTest.java:5: error: cannot find symbol 
    @Test 
^
    symbol: class Test 
    location: class CalculatorTest 
/Users/wogsland/Projects/gradling/src/test/CalculatorTest.java:9: error: cannot find symbol 
    assertEquals(6, sum); 
    ^
    symbol: method assertEquals(int,int) 
    location: class CalculatorTest 
5 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. 

所以我有這個build.gradle文件:

apply plugin: 'java' 

dependencies { 
    testCompile 'junit:junit:4.12' 
} 

sourceSets { 
    main { 
    java { 
     srcDir 'src' 
    } 
    } 
} 

而且CalculatorTest.java

import static org.junit.Assert.assertEquals; 
import org.junit.Test; 

public class CalculatorTest { 
    @Test 
    public void evaluatesExpression() { 
    Calculator calculator = new Calculator(); 
    int sum = calculator.evaluate("1+2+3"); 
    assertEquals(6, sum); 
    } 
} 

但我不明白爲什麼它沒有找到junit,當我將它包含在依賴關係中時。

回答

14

因此很明顯,我需要添加一個compile依賴,然後又宣佈repositories。我的新build.gradle,成功運行測試:

apply plugin: 'java' 

repositories { jcenter() } 
dependencies { 
    testCompile 'junit:junit:4.12' 
    compile 'junit:junit:4.12' 
} 

sourceSets { 
    main { 
     java { 
      srcDir 'src' 
     } 
    } 
} 
+1

請參閱https://issuetracker.google.com/issues/37098629:如果您更改了'sourceSets',Gradle在單元測試中被打破,您必須將junit編譯到生產APK中。 – WillC

0

嘗試增加

repositories { 
    maven { url 'http://repo1.maven.org/maven2' } 

直接在buildscript {下的build.gradle

+0

所以,錯過'buildscript {'可能是問題? – wogsland

+0

上面的'build.gradle'實際上就是我所有的。 – wogsland

相關問題