source code
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();
}
}
prepare build.gradle and apply java plugin
apply plugin: ‘java'
compile java
$ gradle compileJava
BUILD SUCCESSFUL in 620ms
1 actionable task: 1 executed
Clean classes
$ gradle clean
BUILD SUCCESSFUL in 564ms
1 actionable task: 1 executed
Build code and run test
Add junit dependency
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
testCompile 'junit:junit:4.12'
}
Add test code
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);
}
}
Compile and Test
$ 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
Test Report
Open in browser: build/reports/tests/test/index.html
沒有留言:
張貼留言