在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 ')' 

语法很简单:

 @Test(expected = ArithmeticException::class) 

Kotlin有自己的测试助手包 ,可以帮助做这种单元测试 。 加

 import kotlin.test.* 

而你的测试可以通过使用assertFailWith非常有表现力:

 @Test fun test_arithmethic() { assertFailsWith(ArithmeticException::class) { omg() } } 

确保在你的类路径中有kotlin-test.jar

你可以使用@Test(expected = ArithmeticException::class)或者更好的Kotlin的库方法之一如failsWith()

你可以通过使用泛化泛型和像这样的辅助方法来缩短它:

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

和使用注释的例子:

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

你可以使用KotlinTest 。

在你的测试中,你可以用一个shouldThrow块封装任意代码:

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