【问题标题】:Run unit tests with spring boot, "no runnable methods" error使用 spring boot 运行单元测试,“没有可运行的方法”错误
【发布时间】:2020-09-08 15:01:33
【问题描述】:

我正在使用 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)

我该如何解决这个问题?为什么 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)
    }
}

这是错误的截图:

谢谢

附:这是科特林

【问题讨论】:

  • 您的测试是否使用 @Test 注释? - 请展示您的一些代码(最小集)以了解更多信息并帮助排除故障
  • @blurfus 添加了代码示例。是的,它们被注释了
  • 我们正在使用 Kotlin

标签: spring spring-boot unit-testing kotlin


【解决方案1】:

确实是 JUnit4JUnit5 的混合体。我对 @Ignore@Disabled 的测试也有同样的情况,我不想因为 @Test 而被忽略。

您可以通过更新您的 spring 依赖项并从您的 gradle 中删除 Junit4 依赖项来避免这个问题,这样您就不会混合它们。

  testImplementation("org.springframework.boot:spring-boot-starter-test") {
    exclude(module = "junit")
    exclude(module="junit-vintage-engine")
    exclude(module = "mockito-core")
  }
  testImplementation("org.junit.jupiter:junit-jupiter:5.4.2")
  testImplementation("org.junit.jupiter:junit-jupiter-api")
  testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")

一旦你不需要使用@RunWith(SpringRunner::class),你就可以看到你导入的不同之处,它们应该都包含“jupiter”,你的类可能看起来像这样:

import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test

internal class ExampleTest {

  @Test
  fun test() {
    Assertions.assertTrue(true)
  }
}

【讨论】:

    【解决方案2】:

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

    import org.junit.jupiter.api.Test

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

    如果你想使用 JUnit 4,你应该使用 import:

    import org.junit.Test

    【讨论】:

    • 好收获!使用带有 junit 5 @Test 注释的 junit 4 runner...可能就是这样
    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 2014-10-25
    • 1970-01-01
    • 2015-10-19
    • 2018-11-29
    • 2020-07-28
    • 1970-01-01
    • 2016-12-22
    相关资源
    最近更新 更多