我正在尝试在 Kotlin 中编写一个测试,以确保在特定情况下抛出未经检查的异常。
我正在尝试像这样使用 org.junit.jupiter.api.Assertions.assertThrows
:
assertThrows(MyRuntimeException::class, Executable { myMethodThatThrowsThatException() })
当我尝试这个时,我得到一个
Type inference failed compiler error
因为我的 Exception
不是 CheckedException
而是 RuntimeException
。有没有什么好的方法可以在不进行幼稚的 try catch 的情况下测试这种行为?
最佳答案
您可以使用 assertFailsWith来自 Kotlin 标准库:
assertFailsWith<MyRuntimeException> { myMethodThatThrowsThatException() }
关于exception - 如何在 Kotlin 中测试预期的未经检查的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48812309/