Testing plugins which use project.properties set in gradle.properties


(Kushal Kadaba) #1

My custom plugin uses project.properties.. Eventually, this value will be set in gradle.properties of the project where the plugin is applied, but how can I test this while writing tests. I tried
> Project project = ProjectBuilder.build();

project.properties["someVar"] = "abc"

This didn’t work.

I also tried replicating the project structure with
> ProjectBuilder builder = ProjectBuilder.builder();

        Project rootProject = builder.withName("Root").withProjectDir(new File("testDir/root")).build();
        Project project = builder.withName("app").withProjectDir(new     File("testDir/root/app")).withParent(rootProject).build()

and created a gradle.properties in the testDir/root/app folder. Still project.properties.hasProperty("someVar") returns null.

(Mark Vieira) #2

Try the following:

def project = ProjectBuilder.builder().build()
project.ext.foo = 'bar'
assert project.hasProperty('foo')

(Kushal Kadaba) #3

Thanks!! It works, but with one small problem. Properties set in gradle.properties can be directly accessed like variables from build.gradle according to the documentation. I assume we should be able to do that from plugins as well. However, setting the property like this, we cannot use foo like a variable.

(Mark Vieira) #4

You should be able to access it in your test as project.foo. The reason you can access foo as an implicit variable in a build script is because the script itself is delegating to the Project object. This isn’t going to be the case in your test, but you can simulate this somewhat by using with { }

def project = ProjectBuilder.builder().build()
project.with {
    ext {
        foo = 'bar'

    assert foo == 'bar'