在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 has its own test helper package可以帮助做这种单元测试。加
import kotlin.test.*
使用assertFailWith
你的测试可以非常有表现力:
@Test
fun test_arithmethic() {
assertFailsWith(ArithmeticException::class) {
omg()
}
}
确保在课程路径中有kotlin-test.jar
。
您可以使用@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() {
}
你可以使用KotlinTest。
在测试中,您可以使用shouldThrow块包装任意代码:
shouldThrow<ArithmeticException> {
// code in here that you expect to throw a ArithmeticException
}
您还可以在kotlin.test包中使用泛型:
import kotlin.test.assertFailsWith
@Test
fun testFunction() {
assertFailsWith<MyException> {
// The code that will throw MyException
}
}
JUnit 5.1内置了kotlin support。
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
class MyTests {
@Test
fun `division by zero -- should throw ArithmeticException`() {
assertThrows<ArithmeticException> { 1 / 0 }
}
}