JUnit 5 from Groovy

Spock is not the only test framework a Groovy project uses. JUnit 5 works with Groovy classes: the annotations are the Java ones, the assertions are the Java ones, and groovyc compiles the test next to the class under test. A project that already has JUnit tests can add Groovy tests to the same run.

The class under test

Adder.groovy

class Adder { int add(int a, int b) { a + b } }

The test class

AdderTest.groovy

import org.junit.jupiter.api.Test import static org.junit.jupiter.api.Assertions.assertEquals import static org.junit.jupiter.api.Assertions.assertThrows class AdderTest { private final Adder adder = new Adder() @Test void addsTwoNumbers() { assertEquals(5, adder.add(2, 3)) } @Test void refusesAnOverflow() { assertThrows(ArithmeticException) { Math.addExact(Integer.MAX_VALUE, 1) } } }

assertEquals compares with equals, and assertThrows takes the expected type and a closure: the exception the closure throws must be of that type. A test method is any method with @Test, also one without a return type, which is the Groovy habit.

Compile and run

The compiler needs the JUnit API and the launcher needs the Groovy runtime. The console launcher jar in /opt/java-tools carries the engine as well, so the command is two steps:

groovyc -cp /opt/java-tools/junit-platform-console-standalone.jar -d out *.groovy
junit execute --class-path "out:/opt/java-tools/junit-platform-console-standalone.jar:/opt/groovy/lib/groovy-5.0.8.jar" --select-class AdderTest --disable-ansi-colors


Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ AdderTest ✔
│ ├─ addsTwoNumbers() ✔
│ └─ refusesAnOverflow() ✔
└─ JUnit Vintage ✔

Test run finished after <ms> ms
[ 4 containers found ]
[ 0 containers skipped ]
[ 4 containers started ]
[ 0 containers aborted ]
[ 4 containers successful ]
[ 0 containers failed ]
[ 2 tests found ]
[ 0 tests skipped ]
[ 2 tests started ]
[ 0 tests aborted ]
[ 2 tests successful ]
[ 0 tests failed ]

The tree is JUnit's own, with one leaf per test method. In a build the two steps are one test task, and the Gradle lesson shows where the dependency and the launcher go.

Related

Article author: Arthur Isaev