运行 Groovy 个 JUnit 5 测试用例
Running Groovy test cases with JUnit 5
也许这很简单,但我在网上找不到任何例子:
我想使用 JUnit 5 运行 作为 Groovy class 实现的单元测试。我当前的设置似乎启动了 JUnit 5,但未能检测到测试用例。 IntelliJ 识别测试,但未能 运行 它。如果我添加 Java 单元测试,它会正确启动。
这是我现在拥有的:
项目结构
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.
有什么想法吗?
JUnit 要求所有测试方法使用 return 类型 void
。 Groovy 的 def
关键字被编译为 Object
类型,因此您的方法在 Java:
中编译为类似这样的内容
import org.junit.jupiter.api.Test
public class UnitTest {
@Test
Object shouldDoStuff() {
throw new RuntimeException();
}
}
如果您将其作为 Java 测试进行尝试,它也不会找到测试用例。解决方案非常简单 - 将 def
替换为 void
和你的 Groovy
测试用例将被正确执行。
src/test/groovy/UnitTest.groovy
import org.junit.jupiter.api.Test
class UnitTest {
@Test
void shouldDoStuff() {
throw new RuntimeException()
}
}
演示:
也许这很简单,但我在网上找不到任何例子:
我想使用 JUnit 5 运行 作为 Groovy class 实现的单元测试。我当前的设置似乎启动了 JUnit 5,但未能检测到测试用例。 IntelliJ 识别测试,但未能 运行 它。如果我添加 Java 单元测试,它会正确启动。
这是我现在拥有的:
项目结构
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.
有什么想法吗?
JUnit 要求所有测试方法使用 return 类型 void
。 Groovy 的 def
关键字被编译为 Object
类型,因此您的方法在 Java:
import org.junit.jupiter.api.Test
public class UnitTest {
@Test
Object shouldDoStuff() {
throw new RuntimeException();
}
}
如果您将其作为 Java 测试进行尝试,它也不会找到测试用例。解决方案非常简单 - 将 def
替换为 void
和你的 Groovy
测试用例将被正确执行。
src/test/groovy/UnitTest.groovy
import org.junit.jupiter.api.Test
class UnitTest {
@Test
void shouldDoStuff() {
throw new RuntimeException()
}
}
演示: