unit-testing - 在 Kotlin 中测试预期的异常

标签 unit-testing kotlin testing exception junit4

在 Java 中,程序员可以像这样为 JUnit 测试用例指定预期的异常:

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

我将如何在 Kotlin 中执行此操作?我尝试了两种语法变体,但都没有奏效:

import org.junit.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 ')'

最佳答案

JUnit 4.12 的 Java 示例的 Kotlin 翻译为:

@Test(expected = ArithmeticException::class)
fun omg() {
    val blackHole = 1 / 0
}

但是,JUnit 4.13 introduced两个 assertThrows 方法用于更细粒度的异常范围:

@Test
fun omg() {
    // ...
    assertThrows(ArithmeticException::class.java) {
        val blackHole = 1 / 0
    }
    // ...
}

两个 assertThrows 方法都返回预期的额外断言异常:

@Test
fun omg() {
    // ...
    val exception = assertThrows(ArithmeticException::class.java) {
        val blackHole = 1 / 0
    }
    assertEquals("/ by zero", exception.message)
    // ...
}

关于unit-testing - 在 Kotlin 中测试预期的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30331806/

相关文章:

ruby-on-rails - 没有数据库的 Rspec 测试

angularjs - Protractor :如何扩展 Protractor 库?

python - 名称错误 : name 'METHOD_NAME' is not defined Python Unittest

android - bundle 中实现 Material 设计的问题

android - 为什么不是字符串方法返回 Kotlin.Unit?

kotlin - 如何在 kotlin 中强制执行空安全注释检查?

node.js - 如何与 NodeJS、Jest 和 Knex 并行运行 Postgres 测试?

unit-testing - Grails 1.3.5 Controller 测试空命令对象

javascript - 使用模拟 $resource 在 AngularJS 中进行单元测试

java - 使用文件输入的 Junit 参数化测试