Coming Up for Air

Gradle Tip: Attaching a Debugger

Maven offers a nice script to allow for attaching a debugger to your build, mvnDebug. Gradle does not. Again, though, Gradle makes it pretty easy to add this to your build.

Let’s say you want to debug your tests:

build.gradle
1
2
3
4
5
6
test {
    if (System.getProperty('DEBUG', 'false') == 'true') {
        jvmArgs '-Xdebug',
            '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9009'
    }
}

From the command line, issue gradle -DDEBUG=true test:

1
2
3
4
5
6
7
8
9
10
$ gradle -DDEBUG=true test
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava
:processTestResources UP-TO-DATE
:testClasses
:test
Listening for transport dt_socket at address: 9009
> Building > :test

When you see that line, you can attach the debugger of your choice, using port 9009. This also works if you’re building a command line application:

build.gradle
1
2
3
4
5
6
run {
    if (System.getProperty('DEBUG', 'false') == 'true') {
        jvmArgs '-Xdebug',
            '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9009'
    }
}

and run:

1
2
3
4
5
6
7
gradle -DDEBUG=true run
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
Listening for transport dt_socket at address: 9009
> Building > :run

To add this all of your projects, you can make this change to init.gradle:

$HOME/.gradle/init.gradle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
allprojects {
    tasks.withType(Test) {
        if (System.getProperty('DEBUG', 'false') == 'true') {
            jvmArgs '-Xdebug',
                '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9009'
        }
    }

    tasks.withType(JavaExec) {
        if (System.getProperty('DEBUG', 'false') == 'true') {
            jvmArgs '-Xdebug',
                '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9009'
        }
    }
}
tags: Gradle testing

Quotes

Sample quote

Quote source