在 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/