scalaexceptionspecs2

How to get spec2 to show full stack trace with `not(throwA(...))`


If I have a specs2 test like the following:

import org.specs2.mutable.Specification
import scala.util.Try

class Tests extends Specification {

  def foo(): Unit = throw new Exception("oops")
  
  "test" should {
    "not throw an error" in {
      Try(foo()) must beSuccessfulTry
    }
  }
}

specs2.run(new Tests)

(scastie)

Then I get the following output:

[info] test should
[error]   x not throw an error
[error]    Got the exception java.lang.Exception: oops (main.scala:11)

Notice that it doesn't include the stack trace for the actual exception that was thrown. This makes it a lot harder to

And myFunction throws an exception, then the error report just shows the stack trace for the failure for failing to match, since an exception was thrown. This makes it more difficult to figure out what went wrong.

Is there any way for me to get the full stacktrace for the original exception?

Is there a better way to write an expectation that something shouldn't throw an exception?


Solution

  • The Try matchers are more or less equivalent to Option matchers at the moment. This should probably be improved but you can easily work around this limitation by creating your own matcher:

    import org.specs2.matcher.*
    import org.specs2.execute.*
    
    def beOk[T]: Matcher[Try[T]] = (t: scala.util.Try[T]) =>
      t match {
        case scala.util.Success(_) => success
        case scala.util.Failure(e) => Error(e)
      }
    

    and use it like so:

    "test" should {
      "not throw an error" in {
        Try(foo()) must beOk
      }
    }