Gradle how to use custom buildFile with projectBuilder

plugins

(David Gamba) #1

I am trying to pass a custom buildFile to ProjectBuilder:

    given:
    File tempDir = File.createTempDir()
    File buildFile = new File(tempDir,'build.gradle')
    buildFile << """
        plugins {
            id 'com.myplugin.gradle'
        }
    """

    when:
    Project project = new ProjectBuilder()
            .builder()
            .withProjectDir(tempDir)
            .build()

    then:
    project.getProjectDir() ==  tempDir
    project.tasks.getByName("oneOfMyTasks") != null

However, that buildFile is not getting applied.
When I apply it directly, it does work:

    when:
    def project = new ProjectBuilder().build()
    project.plugins.apply('com.myplugin.gradle')

    then:
    project.tasks.getByName("oneOfMyTasks") != null

How do I provide a custom buildFile to ProjectBuilder?

My end goal is to be able to test the correct project properties are applied when using an extension.

    buildFile << """
        plugins {
            id 'com.myplugin.gradle'
        }
        MyPluginExtension {
            foo = "bar"
        }
    """

(Sterling Greene) #2

When you have multiple interacting things (like tasks/extensions/other plugins), you should just use Gradle TestKit. The ProjectBuilder isn’t a full Gradle runtime environment, so it can’t test everything in the same way as a “real” Gradle build.


(Benjamin Muschko) #3

Hi David,

A guide on testing Gradle plugins is going to published soon (likely sometime next week). It will give you a good overview on the different testing approaches. I will link to it as soon as it is ready.

Cheers,

Ben


(David Gamba) #4

Thank you for the suggestion @sterling. My problem with the GradleRunner option is that it doesn’t allow me to query the project, it seems to me that I can only run tasks with it and test on the results of the task.

@bmuschko thanks! I am looking forward to seeing that guide.


(Benjamin Muschko) #5

My problem with the GradleRunner option is that it doesn’t allow me to query the project, it seems to me that I can only run tasks with it and test on the results of the task.

You have access to the full Gradle API. The approach would simply look different. In the build script under test you’d write a task that verifies what you need. From the GradleRunner API you execute that task.

Example:

task verifyProjectDir {
    doLast {
        assert project.projectDir == ...
    }
}

To see if a task has been created run the dependencies task in your functional test and verify the output.


(Benjamin Muschko) #6

@DavidGamba The testing guide has been published: https://guides.gradle.org/testing-gradle-plugins/


(David Gamba) #7

Thank you for the suggestion. This did it for me! :slight_smile: