Search code examples
scalascalatest

How to use ScalaTest Matcher to Test Failure Exception Type?


Given a scala function that can produces Failures:

def testableFunction(x: Int) : Try[Int] = {
  if(x == 0)
    Failure[Int](new IllegalArgumentException("0 is bad"))
  else if(x == 1)
    Failure[Int](new Exception("1 not so good either"))
  else
    Success(42)
}

How can scalatest matchers be used to test the Exception type?

I'm looking for something of the form:

testableFunction(0).failure.type should be IllegalArgumentException

testableFunction(1).failure.type should be Exception

Thank you in advance for your consideration and response.


Solution

  • Mix in the TryValues trait:

    class ExampleTestSpec extends Matchers with TryValues {
      ...
      testableFunction(0).failure.exception shouldBe a [IllegalArgumentException]
    }