ceran ceran - 1 month ago 8
Scala Question

How to check which exception is contained in a Failure[T]?

I'm wondering about the best way to check the content of a failed

Try
using ScalaTest. What I'm doing at the moment looks like this:

"Subject" should "throw proper exceptions.." in {
a[IllegalArgumentException] should be thrownBy {
val tryValue = // some method call..
if (tryValue.isFailure) throw tryValue.failed.get
}
}


As you can see, I just unwrap the exception and throw it manually. Is there a more idiomatic way to achieve the same thing?

Answer

I'd go with something that doesn't really throw the exception, given that a Failure result is just another result that can be matched:

"Subject" should "throw proper exceptions.." in {
  val tryValue = // some method call...
  tryValue shouldBe a[Failure[_]]
  tryValue.failed.get shouldBe an[IllegalArgumentException]
}

The above separates the assertions: you'll see different test failures for the case where no failure happened and the case where the wrong failure happened.

Comments