Guide for Testing Gradle Scripts

后端 未结 3 758
长情又很酷
长情又很酷 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 16:01

    I think what tom meant is a way to test his own written gradle tasks, right? If you have written a custom gradle task by extending DefaultTask and you put it in the buildSrc folder of your project, you can add a junit/spock/whatever based test class to test your task implementation. Gradles own build provides a good example for that. have a look at

    https://github.com/gradle/gradle/blob/master/buildSrc/src/test/groovy/org/gradle/build/docs/dsl/source/ExtractDslMetaDataTaskTest.groovy

    This is a spock specification, that tests the ExtractDslMetaDataTask which was specifically written for griddles own build. The ExtractDslMetaDataTask is located at:

    https://github.com/gradle/gradle/blob/master/buildSrc/src/main/groovy/org/gradle/build/docs/dsl/source/ExtractDslMetaDataTask.groovy

    To add assertions to your build script "adhoc tasks" like your example above you can use the groovy power assertion.

    an example: if you have a a very simple task like this in your script:

    task writeFoo << {
        file("$buildDir/foo.txt").text =  "bar"
    }
    

    you can either modify the task itself to add an assertion:

    task writeFoo << {
        file("$buildDir/foo.txt").text =  "bar"
        assert file("$buildDir/foo.txt).isFile()
    }
    

    or you add a dedicated test task to your script

    task testWriteFoo(dependsOn: writeFoo) << {
        assert file("$buildDir/foo.txt).isFile()
        assert file("$buildDir/foo.txt).text == "bar"
    }
    

    remember that you can use the full power of the groovy language in your build scripts.

    There are plans to have an integrated testing toolkit in gradle to support build script authors on testing their custom build logic. have a look at:

    http://forums.gradle.org/gradle/topics/testing_toolkit_for_custom_build_logic

提交回复
热议问题