Gradle Java 專案 - 程式碼與測試
原始碼
Hello.java
package examples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Hello {
public String hello() throws IOException {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("hello.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder s = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
s.append(line);
}
return s.toString();
}
}
準備 build.gradle 並套用 java plugin
apply plugin: 'java'
編譯 Java
$ gradle compileJava
BUILD SUCCESSFUL in 620ms
1 actionable task: 1 executed
清除 class 檔案
$ gradle clean
BUILD SUCCESSFUL in 564ms
1 actionable task: 1 executed
建置程式碼並執行測試
加入 junit 依賴
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
testCompile 'junit:junit:4.12'
}
加入測試程式碼
package examples;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.Assert;
import org.junit.Test;
public class HelloTest {
@Test
public void hello() throws IOException, URISyntaxException {
Hello h = new Hello();
String hello = h.hello();
String hellotest = new String(Files.readAllBytes(Paths.get(Thread.currentThread().getContextClassLoader().getResource("hellotest.txt").toURI())));
Assert.assertEquals(hellotest, hello);
}
}
編譯與測試
$ gradle build
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.3/userguide/command_line_interface.html#sec:command_line_warnings
BUILD SUCCESSFUL in 1s
6 actionable tasks: 6 executed
測試報告
用瀏覽器開啟:build/reports/tests/test/index.html
接下來看什麼
延伸閱讀