测试Kotlin中的预期异常

时间:2015-05-19 17:01:27

标签: unit-testing exception testing kotlin

在Java中,程序员可以为JUnit测试用例指定预期的异常,如下所示:

@Test(expected = ArithmeticException.class)
public void omg()
{
    int blackHole = 1 / 0;
}

我如何在Kotlin做到这一点?我尝试了两种语法变体,但没有一种工作:

import org.junit.Test as test

// ...

test(expected = ArithmeticException) fun omg()
    Please specify constructor invocation;
    classifier 'ArithmeticException' does not have a companion object

test(expected = ArithmeticException.class) fun omg()
                           name expected ^
                                           ^ expected ')'

11 个答案:

答案 0 :(得分:66)

语法很简单:

@Test(expected = ArithmeticException::class)

答案 1 :(得分:51)

Kotlin has its own test helper package可以帮助做这种单元测试。添加

import kotlin.test.*

使用assertFailWith

,您的测试非常具有表现力
@Test
fun test_arithmethic() {
    assertFailsWith(ArithmeticException::class) {
        omg()
    }
}

确保在您的课程路径中有kotlin-test.jar

答案 2 :(得分:18)

您可以使用@Test(expected = ArithmeticException::class)或更好的Kotlin库方法,例如failsWith()

您可以使用reified泛型和这样的辅助方法使其更短:

inline fun <reified T : Throwable> failsWithX(noinline block: () -> Any) {
    kotlin.test.failsWith(javaClass<T>(), block)
}

使用注释的示例:

@Test(expected = ArithmeticException::class)
fun omg() {

}

答案 3 :(得分:11)

您可以使用KotlinTest

在测试中,您可以使用shouldThrow块包装任意代码:

shouldThrow<ArithmeticException> {
  // code in here that you expect to throw a ArithmeticException
}

答案 4 :(得分:4)

你也可以在kotlin.test包中使用泛型:

if (o->ob_type->tp_as_number and o->ob_type->tp_as_number->nb_int) {
    do_whatever();
}

答案 5 :(得分:2)

JUnit 5.1内置kotlin support

"missing ;"

答案 6 :(得分:1)

声明扩展名,以验证异常类以及错误消息是否匹配。

inline fun <reified T : Exception> assertThrows(runnable: () -> Any?, message: String?) {
try {
    runnable.invoke()
} catch (e: Throwable) {
    if (e is T) {
        message?.let {
            Assert.assertEquals(it, "${e.message}")
        }
        return
    }
    Assert.fail("expected ${T::class.qualifiedName} but caught " +
            "${e::class.qualifiedName} instead")
}
Assert.fail("expected ${T::class.qualifiedName}")

}

例如:

assertThrows<IllegalStateException>({
        throw IllegalStateException("fake error message")
    }, "fake error message")

答案 7 :(得分:1)

没有人提到assertFailsWith()返回值,您可以检查异常属性:

view('shop::page.privacy')

答案 8 :(得分:0)

另一种语法版本使用的是kluent

@Test
fun `should throw ArithmeticException`() {
    invoking {
        val backHole = 1 / 0
    } `should throw` ArithmeticException::class
}

答案 9 :(得分:0)

正确的步骤是在测试注释中添加(expected = YourException::class)

@Test(expected = YourException::class)

第二步是添加此功能

private fun throwException(): Boolean = throw YourException()

最后,您将得到如下内容:

@Test(expected = ArithmeticException::class)
fun `get query error from assets`() {
    //Given
    val error = "ArithmeticException"

    //When
    throwException()
    val result =  omg()

    //Then
    Assert.assertEquals(result, error)
}
private fun throwException(): Boolean = throw ArithmeticException()

答案 10 :(得分:0)

org.junit.jupiter.api.Assertions.kt

MigrationObject