如何在 Kotlin 中测试预期的未经检查的异常?
How do I test expected Unchecked Exceptions in Kotlin?
我正在尝试用 Kotlin 编写一个测试,以确保在特定情况下抛出未经检查的异常。
我正在尝试这样使用 org.junit.jupiter.api.Assertions.assertThrows
:
assertThrows(MyRuntimeException::class, Executable { myMethodThatThrowsThatException() })
当我尝试这个时,我得到一个
Type inference failed compiler error
因为我的 Exception
不是 CheckedException
而是 RuntimeException
。有什么好的方法可以在不进行幼稚的 try catch 的情况下测试这种行为吗?
assertThrows
方法需要一个 Class
作为它的第一个参数,但你试图给它一个 KClass
。要解决此问题,只需执行以下操作(如文档 here 中所述):
assertThrows(MyRuntimeException::class.java, Executable { myMethodThatThrowsThatException() })
您也可以省略显式 Executable
类型:
assertThrows(MyRuntimeException::class.java, { myMethodThatThrowsThatException() })
或者如果你的方法真的不接受任何参数,你可以使用方法引用它:
assertThrows(MyRuntimeException::class.java, ::myMethodThatThrowsThatException)
您可以使用 Kotlin 标准库中的 assertFailsWith:
assertFailsWith<MyRuntimeException> { myMethodThatThrowsThatException() }
我正在尝试用 Kotlin 编写一个测试,以确保在特定情况下抛出未经检查的异常。
我正在尝试这样使用 org.junit.jupiter.api.Assertions.assertThrows
:
assertThrows(MyRuntimeException::class, Executable { myMethodThatThrowsThatException() })
当我尝试这个时,我得到一个
Type inference failed compiler error
因为我的 Exception
不是 CheckedException
而是 RuntimeException
。有什么好的方法可以在不进行幼稚的 try catch 的情况下测试这种行为吗?
assertThrows
方法需要一个 Class
作为它的第一个参数,但你试图给它一个 KClass
。要解决此问题,只需执行以下操作(如文档 here 中所述):
assertThrows(MyRuntimeException::class.java, Executable { myMethodThatThrowsThatException() })
您也可以省略显式 Executable
类型:
assertThrows(MyRuntimeException::class.java, { myMethodThatThrowsThatException() })
或者如果你的方法真的不接受任何参数,你可以使用方法引用它:
assertThrows(MyRuntimeException::class.java, ::myMethodThatThrowsThatException)
您可以使用 Kotlin 标准库中的 assertFailsWith:
assertFailsWith<MyRuntimeException> { myMethodThatThrowsThatException() }