使用JUnit 5运行Groovy测试用例 [英] Running Groovy test cases with JUnit 5

查看:386
本文介绍了使用JUnit 5运行Groovy测试用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这很简单,但是我在网络上找不到任何示例:

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

我想使用JUnit 5运行作为Groovy类实现的单元测试.我当前的设置似乎启动了JUnit 5,但是无法检测到测试用例. IntelliJ可以识别测试,但无法运行.如果我添加了Java单元测试,则它会正确启动.

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.

这就是我现在拥有的:

项目结构

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()
    }
}

我正在使用Gradle 4.10.

I'm using Gradle 4.10.

有什么想法吗?

推荐答案

JUnit要求所有测试方法都使用返回类型void. Groovy的def关键字被编译为Object类型,因此您的方法在Java中将编译为以下内容:

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();
    }
}

如果您将其作为Java测试进行尝试,则也不会找到该测试用例.解决方案非常简单-用void和您的Groovy替换def 测试用例将正确执行.

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()
    }
}

演示:

这篇关于使用JUnit 5运行Groovy测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆