How to properly test exceptions in Kotlin with JUnit?
Hello everyone! I'm new to Kotlin and trying to write unit tests for my project. Previously I wrote in Java, where I used `@Test(expected = ...)` or `try-catch` blocks to check exceptions. But in Kotlin I ran into a problem — the code became less readable, and I'm not sure I'm doing everything correctly.
I have a function `divide(a: Int, b: Int): Int` that throws `IllegalArgumentException` if the divisor is zero. Here's how I tried to test it:
```kotlin
@Test
fun testDivisionByZero() {
try {
divide(10, 0)
fail("Exception expected")
} catch (e: IllegalArgumentException) {
// success
}
}
```
This works, but looks cumbersome. I've heard that Kotlin has more modern approaches, for example, using `assertThrows` from JUnit 5.
No answers yet.
Log in to leave an answer