使用 Spring Boot 运行单元测试,出现“无可运行方法”错误

Jen*_*nov 5 spring unit-testing kotlin spring-boot

我正在使用 Spring boot 运行单元测试,但出现了一个奇怪的no runnable错误。测试通过了,但是在所有测试成功结束之后,我突然得到这个奇怪的错误:

java.lang.Exception: No runnable methods

at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:191)
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:128)
at org.junit.runners.ParentRunner.validate(ParentRunner.java:416)
at org.junit.runners.ParentRunner.<init>(ParentRunner.java:84)
at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:65)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:137)
at org.springframework.test.context.junit4.SpringRunner.<init>(SpringRunner.java:49)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
Run Code Online (Sandbox Code Playgroud)

我该如何解决?为什么 Spring boot 在我的测试中寻找可运行程序?

这是我的代码的示例

package ca.bell.uc.hello.world

import org.junit.Assert
import org.junit.jupiter.api.Test
import org.junit.runner.RunWith
import org.springframework.test.context.junit4.SpringRunner


@RunWith(SpringRunner::class)
internal class example {

    @Test
    fun f() {
        Assert.assertTrue(true)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是错误的屏幕截图:

在此输入图像描述

谢谢

PS 这是 Kotlin

小智 7

@Test由于导入,您尝试使用 JUnit 5注释:

import org.junit.jupiter.api.Test

在控制台日志中我们可以看到使用的是JUnit 4。

如果您想使用 JUnit 4,您应该使用导入:

import org.junit.Test