Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Groovy test cases with JUnit 5

Tags:

groovy

junit5

Maybe this is very simple, but I couldn't find any examples on the web:

I'd like to use JUnit 5 to run a unit test implemented as a Groovy class. My current setup seems to launch JUnit 5, but fail to detect the test case. IntelliJ recognizes the test, but fails to run it. If I add a Java unit test, it is launched correctly.

Here's what I have now:

Project structure

src
  main
    groovy
      # production code
  test
    groovy
      UnitTest.groovy
build.gradle
...

build.gradle

plugins {
    id 'groovy'
}

dependencies {
    compile localGroovy()

    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.1.1'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.1.1'
}

test {
    useJUnitPlatform()
}

UnitTest.groovy

import org.junit.jupiter.api.Test

class UnitTest {

    @Test
    def shouldDoStuff() {
        throw new RuntimeException()
    }
}

I'm using Gradle 4.10.

Any ideas?

like image 526
pstobiecki Avatar asked Dec 13 '22 14:12

pstobiecki


1 Answers

JUnit requires all testing method to use return type void. Groovy's def keyword is compiled to an Object type, so your method compiles to something like this in Java:

import org.junit.jupiter.api.Test

public class UnitTest {

    @Test
    Object shouldDoStuff() {
        throw new RuntimeException();
    }
}

If you try this out as a Java test, it won't find the test case neither. The solution is very simple - replace def with void and your Groovy test case will be executed correctly.


src/test/groovy/UnitTest.groovy

import org.junit.jupiter.api.Test

class UnitTest {

    @Test
    void shouldDoStuff() {
        throw new RuntimeException()
    }
}

Demo:

asciicast

like image 196
Szymon Stepniak Avatar answered Dec 24 '22 12:12

Szymon Stepniak