例外が発生するのをテストにするには intercept
を使う。
ExampleTestSuite.scala
import org.scalatest._
class ExampleTestSuite extends FunSuite with Matchers {
test("invalid status transition") {
val s = "hi"
intercept[IndexOutOfBoundsException] {
s.charAt(-1)
}
}
}
BDDらしく書く場合は、should be thrownBy
、 thrownBy
、 noException should be thrownBy
などが使える
ExampleSpec.scala
import org.scalatest._
class ExampleSpec extends FeatureSpec with Matchers {
scenario("Throws exception") {
an[IndexOutOfBoundsException] should be thrownBy "".charAt(-1)
}
scenario("Throws exception with message") {
val thrown = the[IndexOutOfBoundsException] thrownBy "".charAt(-1)
thrown.getMessage shouldBe "String index out of range: -1"
}
scenario("Throws no exception") {
noException should be thrownBy "a".charAt(0)
}
}