What are the best practices for testing Gradle Scripts?
I currently unit test my ant scripts with antunit, but I\'m looking to migrate to Gradle. I can only find art
Gradle 3.x test Toolkit available! Please, check out userguide here: https://docs.gradle.org/current/userguide/test_kit.html
The correctness of the logic can then be verified by asserting the following, potentially in combination:
copy-pasted example:
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.gradle.testkit.runner.TaskOutcome.*;
public class BuildLogicFunctionalTest {
@Rule public final TemporaryFolder testProjectDir = new TemporaryFolder();
private File buildFile;
@Before
public void setup() throws IOException {
buildFile = testProjectDir.newFile("build.gradle");
}
@Test
public void testHelloWorldTask() throws IOException {
String buildFileContent = "task helloWorld {" +
" doLast {" +
" println 'Hello world!'" +
" }" +
"}";
writeFile(buildFile, buildFileContent);
BuildResult result = GradleRunner.create()
.withProjectDir(testProjectDir.getRoot())
.withArguments("helloWorld")
.build();
assertTrue(result.getOutput().contains("Hello world!"));
assertEquals(result.task(":helloWorld").getOutcome(), SUCCESS);
}
private void writeFile(File destination, String content) throws IOException {
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(destination));
output.write(content);
} finally {
if (output != null) {
output.close();
}
}
}
}