Last active
September 16, 2023 19:17
-
-
Save lene/6318b26e1507644317f2fb6124b4b96a to your computer and use it in GitHub Desktop.
Scala: assertThrows in Junit5 and hand-rolled
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.