03.03.FlatSpec の始め方

FlatSpec では、テストと、テストされているふるまいを記述したテキストを結合します。

まずテストと仕様に関するサブジェクトを記述し、should, must , can の後につづく動詞とブロックで、説明を記述します。

この動詞の後に、サブジェクトが要求するいくつかのふるまいを記述した残りの文を完成させる文字列を配置します。

その後に in と波括弧でくくったテストコードを記述します。

もし、テストをペンディングにしておきたいなら、in の代わりに is を使います。

また、同じサブジェクトについてさらにふるまいを記述する場合、サブジェクトの文字列を繰り返す代わりに、it を使うこともできます。

基本的な構造は、以下のようになります。

import org.scalatest.FlatSpec

class ExampleSpec extends FlatSpec {

"スタック" should "後入れ先出し順序で値をポップする" is (pending)

it should "スタックが空だった場合、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.FlatSpec

import scala.collection.mutable.Stack

class ExampleSpec extends FlatSpec {

"スタック" should "後入れ先出し順序で値をポップする" in {

val stack = new Stack[Int]

stack.push(1)

stack.push(2)

assert(stack.pop() === 2)

assert(stack.pop() === 1)

}

it should "スタックが空だった場合、NoSuchElementException を投げる" in {

val emptyStack = new Stack[String]

intercept[NoSuchElementException] {

emptyStack.pop()

}

}

}

または、ScalaTest のマッチャーシンタックスがお好みなら、ShouldMatchers や MustMatchers をミックスインすることができます。

import org.scalatest.FlatSpec

import org.scalatest.matchers.ShouldMatchers

import scala.collection.mutable.Stack

class ExampleSpec extends FlatSpec with ShouldMatchers {

"スタック" should "後入れ先出し順序で値をポップする" in {

val stack = new Stack[Int]

stack.push(1)

stack.push(2)

stack.pop() should be === 2

stack.pop() should be === 1

}

it should "スタックが空だった場合、NoSuchElementException を投げる" in {

val emptyStack = new Stack[String]

evaluating { emptyStack.pop() } should 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.