Guide for Testing Gradle Scripts

后端 未结 3 754
长情又很酷
长情又很酷 2020-12-17 15:02

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-17 15:48

    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:

    • The build's output;
    • The build's logging (i.e. console output);
    • The set of tasks executed by the build and their results (e.g. FAILED, UP-TO-DATE etc.).

    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();
                }
            }
        }
    }
    

提交回复
热议问题