Testkit / GradleRunner: How to use a proxy?

444 views Asked by At

For regular gradle actions, I have a gradle.properties file in my project or home which configures the proxy details (host/port etc.)

When using GradleRunner, the gradle.properties file is ignored by intention:
"Any configuration in the default Gradle user home directory (e.g. ~/.gradle/gradle.properties) is not used for test execution. The TestKit does not expose a mechanism for fine grained control of all aspects of the environment (e.g., JDK). Future versions of the TestKit will provide improved configuration options."

(from https://docs.gradle.org/current/userguide/test_kit.html#sec:controlling_the_build_environment)

Question:
How can I configure a proxy when using GradleRunner?

1

There are 1 answers

3
Chriki On BEST ANSWER

You can simply add a gradle.properties file with the proxy settings to your test project (run with GradleRunner). Here’s a complete example project (Gradle 7.1 Wrapper files not shown):

├── build.gradle
└── src
    └── test
        └── groovy
            └── com
                └── example
                    └── MyTest.groovy

build.gradle

plugins {
    id 'groovy'
    id 'java-gradle-plugin'
}

repositories {
  mavenCentral()
}

dependencies {
    testImplementation('org.spockframework:spock-core:2.0-groovy-3.0')
}

test {
    useJUnitPlatform()
}

src/test/groovy/com/example/MyTest.groovy

package com.example

import org.gradle.testkit.runner.GradleRunner
import static org.gradle.testkit.runner.TaskOutcome.*
import spock.lang.TempDir
import spock.lang.Timeout
import spock.lang.Specification

class MyTest extends Specification {

    @TempDir File projDir

    @Timeout(10)
    def "network connection through proxy works"() {
        given:
        def myTestTask = 'foo'
        new File(projDir, 'settings.gradle') << "rootProject.name = 'my-test'"
        new File(projDir, 'gradle.properties') << '''\
            systemProp.http.proxyHost = 192.168.123.123
            '''
        new File(projDir, 'build.gradle') << """\
            task $myTestTask {
                doLast {
                    println(new java.net.URL('http://www.example.com').text)
                }
            }
            """

        when:
        def result = GradleRunner.create()
            .withProjectDir(projDir)
            .withArguments(myTestTask)
            .build()

        then:
        result.task(":$myTestTask").outcome == SUCCESS
    }
}

I’ve used a non-existing dummy proxy which leads to a test failure because of a test/connection timeout (→ SpockTimeoutError). Using a real proxy instead, the test should succeed.