如何在junit5中优雅终止

问题描述 投票:0回答:1

当我在 junit5(5.10.1) 中运行下面的测试时,test1 失败,test2 似乎被跳过,但 test2 不会调用

@AfterEach
。所以资源清理对于 test2 不起作用。

这是junit5的原始行为吗? 这种情况,最好的处理方法是什么?

提前致谢

  • 测试结果
BeforeEach is called!!
test1 is called
AfterEach is called!!

Expected :10
Actual   :1

BeforeEach is called!!
test2 is called(run time consumed logic)

> Task :{module}:test FAILED
SimpleTest > test1() FAILED
    io.kotest.assertions.AssertionFailedError: expected:<10> but was:<1>
        at app//{module}(SimpleTest.kt:20)
2 tests completed, 1 failed, 1 skipped
FAILURE: Build failed with an exception.

  • 测试代码
class SimpleTest {

    @BeforeEach
    fun setup() {
        println("BeforeEach is called!!")
    }

    @Test
    fun test1() {
        println("test1 is called")
        1 shouldBe 10
    }

    @Test
    fun test2() {
        println("test2 is called(run time consumed logic)")
        for (i in 1..500_000_000) {
            sqrt(Math.random())
        }
    }

    @AfterEach
    fun cleanup() {
        println("AfterEach is called!!")
    }
}

junit junit5 junit-jupiter
1个回答
0
投票

您遇到此错误的原因可能是

test2
执行时间可能超出了 JUnit5 定义的某个时间限制。

您可以使用

@AfterAll
注释代替
@AfterEach

@AfterAll
注释可确保在执行测试类中的所有测试后执行该方法,无论是否有任何失败或跳过的测试。

import io.kotest.assertions.ktor.shouldBe
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test

class SimpleTest {

    @BeforeEach
    fun setup() {
        println("BeforeEach is called!!")
    }

    @Test
    fun test1() {
        println("test1 is called")
        1 shouldBe 10
    }

    @Test
    fun test2() {
        println("test2 is called(run time consumed logic)")
        for (i in 1..500_000_000) {
            Math.sqrt(Math.random())
        }
    }

    @AfterAll // <-----------------
    fun cleanup() {
        println("AfterAll is called!!")
    }
}

通过此修改,在执行类中的所有测试(包括 test2)后,将调用 cleanup() 方法,而不管各个测试的结果如何。

© www.soinside.com 2019 - 2024. All rights reserved.