Passing Extra Properties to Test Classes

I’m currently using Spock for testing Groovy code… the Spock may or may not be relevant. What I’m wondering: is there a way to parameterize my Specification/Test classes (Spock or otherwise) with Gradle extra properties from the project? This is mostly around integration testing… and the project extra properties define things like: directory locations, system configurations, credentials, etc. I’m using Spock data pipes, and those properties are necessary for telling those pipes where to get data sets.

Yes, you can pass system properties to your tests using ‘systemProperties()’ method of Test task type.

This becomes problematic if you want your tests to have access to these properties when you run them from the IDE. In such case, generating a properties file and putting it on test classpath might be a solution. You then read the generated resource of the classpath in your tests to get access to these properties.

Following is an example of a build script that adds a generated property file to test classpath in both gradle and IntelliJ:

apply plugin: 'java'
apply plugin: 'idea'
  ext {
    generatedTestResourcesDir = file("$buildDir/generated-test-resources")
  class WriteTestConfig extends DefaultTask {
    Properties testConfig = new Properties()
    File getTestConfigPropertiesFile() {
        new File(project.generatedTestResourcesDir, '')
    def generate() {
        testConfigPropertiesFile.withOutputStream {, null) }
  task configureWriteTestConfig {
    doLast {
        writeTestConfig.testConfig[""] = "someTestValue"
  task writeTestConfig(type: WriteTestConfig) {
    dependsOn configureWriteTestConfig
  sourceSets.test.resources.srcDir generatedTestResourcesDir
  processTestResources.dependsOn writeTestConfig
ideaModule.dependsOn writeTestConfig
1 Like