Excepciones
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
Para verificar que un bloque de código lanza una excepción, puedes usar la función shouldThrow. Por ejemplo:
shouldThrow<IllegalAccessException> {
// code in here that you expect to throw an IllegalAccessException
}
También puedes comprobar la excepción capturada:
val exception = shouldThrow<IllegalAccessException> {
// code in here that you expect to throw an IllegalAccessException
}
exception.message should startWith("Something went wrong")
Si necesitas probar que se lanza un tipo específico de excepción, usa shouldThrowExactly<E>. Por ejemplo, el siguiente bloque capturaría una FileNotFoundException pero no una IOException, a pesar de que FileNotFoundException hereda de IOException.
val exception = shouldThrowExactly<FileNotFoundException> {
// test here
}
Si simplemente quieres verificar que se lanza cualquier excepción, sin importar el tipo, utiliza shouldThrowAny.
val exception = shouldThrowAny {
// test here can throw any type of Throwable!
}
Si necesitas verificar que no se lanza ninguna excepción, usa shouldNotThrowAny.
shouldNotThrowAny {
// test here should not throw any type of Throwable!
}