03.02.WordSpec の始め方
WordSpec では、テストと、テストされているふるまいを記述したテキストを結合します。
まずテストと仕様に関するサブジェクトを記述し、should, must , can の後につづく動詞とブロックで、説明を記述します。
このブロックに、サブジェクトが要求するいくつかのふるまいを記述した残りの文を配置します。
その後に in と波括弧でくくったテストコードを記述します。
もし、テストをペンディングにしておきたいなら、in の代わりに is を使います。
基本的な構造は、以下のようになります。
import org.scalatest.WordSpec
class ExampleSpec extends WordSpec {
"スタック" should {
"後入れ先出し順序で値をポップする" is (pending)
"スタックが空だった場合、NoSuchElementException を投げる" is (pending)
}
}
ここで仕様が記載され、テストされているサブジェクトは「スタック」です。
テストがまだ実行されていないことを示すために、"pending"となっています。
Spec をコンパイルするには、以下のように入力します。
$ scalac -cp scalatest-1.5.jar ExampleSpec.scala
実行するには、以下のように入力します。
$ scala -cp scalatest-1.5.jar org.scalatest.tools.Runner -p . -o -s ExampleSpec
Run starting. Expected test count is: 2
ExampleSpec:
スタック
- should 後入れ先出し順序で値をポップする (pending)
- should スタックが空だった場合、NoSuchElementException を投げる (pending)
Run completed in 61 milliseconds.
Total number of tests run: 0
Suites: completed 1, aborted 0
Tests: succeeded 0, failed 0, ignored 0, pending 2
All tests passed.
仕様に関するテキストが、読める形で出力されていることに注目してください。
テストは、以下のように書くことができます。
import org.scalatest.WordSpec
import scala.collection.mutable.Stack
class ExampleSpec extends WordSpec {
"スタック" should {
"後入れ先出し順序で値をポップする" in {
val stack = new Stack[Int]
stack.push(1)
stack.push(2)
assert(stack.pop() === 2)
assert(stack.pop() === 1)
}
"スタックが空だった場合、NoSuchElementException を投げる" in {
val emptyStack = new Stack[String]
intercept[NoSuchElementException] {
emptyStack.pop()
}
}
}
}
または、ScalaTest のマッチャーシンタックスがお好みなら、ShouldMatchers や MustMatchers をミックスインすることができます。
import org.scalatest.WordSpec
import org.scalatest.matchers.MustMatchers
import scala.collection.mutable.Stack
class ExampleSpec extends WordSpec with MustMatchers {
"スタック" should {
"後入れ先出し順序で値をポップする" in {
val stack = new Stack[Int]
stack.push(1)
stack.push(2)
stack.pop() must be === 2
stack.pop() must be === 1
}
"スタックが空だった場合、NoSuchElementException を投げる" in {
val emptyStack = new Stack[String]
evaluating { emptyStack.pop() } must produce [NoSuchElementException]
}
}
}
ExampleSpec を実行してみましょう。もう pending となっているテストはないはずです。
$ scala -cp scalatest-1.5.jar org.scalatest.tools.Runner -p . -o -s ExampleSpec
Run starting. Expected test count is: 2
ExampleSpec:
スタック
- should 後入れ先出し順序で値をポップする
- should スタックが空だった場合、NoSuchElementException を投げる
Run completed in 76 milliseconds.
Total number of tests run: 2
Suites: completed 1, aborted 0
Tests: succeeded 2, failed 0, ignored 0, pending 0
All tests passed.