9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scala: 例外が発生するシナリオをテストする

Last updated at Posted at 2014-02-21

例外が発生するのをテストにするには 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 thrownBythrownBynoException 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)
  }
}
9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?