In Java, the programmer can specify expected exceptions for JUnit test cases like this:
@Test(expected = ArithmeticException.class)
public void omg()
{
int bl
Firt steps is to add (expected = YourException::class)
in test annotation
@Test(expected = YourException::class)
Second step is to add this function
private fun throwException(): Boolean = throw YourException()
Finally you will have something like this:
@Test(expected = ArithmeticException::class)
fun `get query error from assets`() {
//Given
val error = "ArithmeticException"
//When
throwException()
val result = omg()
//Then
Assert.assertEquals(result, error)
}
private fun throwException(): Boolean = throw ArithmeticException()
/**
* Example usage:
* ```kotlin
* val exception = assertThrows<IllegalArgumentException>("Should throw an Exception") {
* throw IllegalArgumentException("Talk to a duck")
* }
* assertEquals("Talk to a duck", exception.message)
* ```
* @see Assertions.assertThrows
*/
inline fun <reified T : Throwable> assertThrows(message: String, noinline executable: () -> Unit): T =
assertThrows({ message }, executable)
Another version of syntaxis using kluent:
@Test
fun `should throw ArithmeticException`() {
invoking {
val backHole = 1 / 0
} `should throw` ArithmeticException::class
}
You can also use generics with kotlin.test package:
import kotlin.test.assertFailsWith
@Test
fun testFunction() {
assertFailsWith<MyException> {
// The code that will throw MyException
}
}
You can use @Test(expected = ArithmeticException::class)
or even better one of Kotlin's library methods like failsWith().
You can make it even shorter by using reified generics and a helper method like this:
inline fun <reified T : Throwable> failsWithX(noinline block: () -> Any) {
kotlin.test.failsWith(javaClass<T>(), block)
}
And example using the annotation:
@Test(expected = ArithmeticException::class)
fun omg() {
}