Testing And Benchmarking in Groovy

Here’s the translation of the Go testing and benchmarking example to Groovy, formatted in Markdown suitable for Hugo:

Unit testing is an important part of writing principled Groovy programs. The JUnit framework provides the tools we need to write unit tests, and the Gradle or Maven build tools can be used to run tests.

For the sake of demonstration, this code is in a single file, but it could be split into separate files. Testing code typically lives in a separate directory but in the same package as the code it tests.

import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource

class IntUtilsTest {
    // We'll be testing this simple implementation of an integer minimum.
    static int intMin(int a, int b) {
        return a < b ? a : b
    }

    // A test is created by writing a method with the @Test annotation.
    @Test
    void testIntMinBasic() {
        int ans = intMin(2, -2)
        Assertions.assertEquals(-2, ans, "IntMin(2, -2) should be -2")
    }

    // Writing tests can be repetitive, so it's idiomatic to use
    // parameterized tests, where test inputs and expected outputs
    // are provided as parameters.
    @ParameterizedTest
    @CsvSource([
        "0, 1, 0",
        "1, 0, 0",
        "2, -2, -2",
        "0, -1, -1",
        "-1, 0, -1"
    ])
    void testIntMinParameterized(int a, int b, int expected) {
        int ans = intMin(a, b)
        Assertions.assertEquals(expected, ans, "IntMin($a, $b) should be $expected")
    }
}

To run the tests, you would typically use a build tool like Gradle. Here’s an example of running tests with Gradle:

$ ./gradlew test

For performance testing in Groovy, you might use a library like JMH (Java Microbenchmark Harness). Here’s a simple example of how you might set up a benchmark:

import org.openjdk.jmh.annotations.*

@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
class IntMinBenchmark {

    @Benchmark
    void benchmarkIntMin() {
        IntUtilsTest.intMin(1, 2)
    }
}

To run benchmarks, you would need to set up JMH in your build file and run it. The exact command would depend on your setup, but it might look something like this:

$ ./gradlew jmh

Remember that Groovy, being a JVM language, leverages much of the Java ecosystem for testing and benchmarking. The concepts are similar, but the exact implementation and tools may differ slightly from what you might use in a static language.