Skip to content

Instantly share code, notes, and snippets.

@lene
Last active September 16, 2023 19:17
Show Gist options
  • Save lene/6318b26e1507644317f2fb6124b4b96a to your computer and use it in GitHub Desktop.
Save lene/6318b26e1507644317f2fb6124b4b96a to your computer and use it in GitHub Desktop.
Scala: assertThrows in Junit5 and hand-rolled
def throwingFunction(): Unit = throw RuntimeError()
// own implementation of assertThrows
def assertThrows[E](f: => Unit)(implicit eType:ClassTag[E]): Unit =
try f
catch
case _: E => return
case e: Any => Assertions.fail(s"Expected ${eType.runtimeClass.getName} got ${e.getClass}")
Assertions.fail(s"Expected ${eType.runtimeClass.getName}")
// usage:
assertThrows[RuntimeError](throwingFunction())
// import assertThrows from jupiter/JUnit5
import org.junit.jupiter.api.Assertions
// usage:
Assertions.assertThrows(classOf[RuntimeError], () => throwingFunction())
@lene
Copy link
Author

lene commented Sep 16, 2023

tbh I like my implementation better, but if you are able to use JUnit5, it is preferable to use the library function.

JUnit4 does not offer an assertThrows, so you may have to use the own implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment