05.FunSuite の始め方
FunSuite では、テストは関数の値です(FunSuiteの"Fun"はfunctionを表しています)。
あなたは、実施するテストを test で示し、テスト名を括弧でくくった文字列で入力します。テストコードは、その後に続きます。
基本的な構造は、以下のようになります。
import org.scalatest.FunSuite
class ExampleSuite extends FunSuite {
test("pop を空でない stack で実施") (pending)
test("pop を空の stack で実施") (pending)
}
テストは"pending"となっていますが、これはまだ本体が実装されていないことを示しています。
このコードをコンパイルするには、コマンドラインから次のように入力してください。
$ scalac -cp scalatest-1.5.jar ExampleSuite.scala
テストを実行するには、以下のように入力します。
$ scala -cp scalatest-1.5.jar org.scalatest.tools.Runner -p . -o -s
ExampleSuite
Run starting. Expected test count is: 2
ExampleSuite:
- pop を空でない stack で実施 (pending)
- pop を空の stack で実施 (pending)
Run completed in 147 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.FunSuite
import scala.collection.mutable.Stack
class ExampleSuite extends FunSuite {
test("pop を空でない stack で実施") {
val stack = new Stack[Int]
stack.push(1)
stack.push(2)
val oldSize = stack.size
val result = stack.pop()
assert(result === 2)
assert(stack.size === oldSize - 1)
}
test("pop を空の stack で実施") {
val emptyStack = new Stack[String]
intercept[NoSuchElementException] {
emptyStack.pop()
}
assert(emptyStack.isEmpty)
}
}
この例では assert を使いましたが、ScalaTest の Matcher シンタックスがお好みなら、 ShouldMatchers や MustMatchers をミックスインすることができます。
import org.scalatest.FunSuite
import org.scalatest.matchers.ShouldMatchers
import scala.collection.mutable.Stack
class ExampleSuite extends FunSuite with ShouldMatchers {
test("pop を空でない stack で実施") {
val stack = new Stack[Int]
stack.push(1)
stack.push(2)
val oldSize = stack.size
val result = stack.pop()
result should equal (2)
stack.size should equal (oldSize - 1)
}
test("pop を空の stack で実施") {
val emptyStack = new Stack[String]
evaluating { emptyStack.pop() } should produce [NoSuchElementException]
emptyStack should be ('empty)
}
}
ExampleSuite を実行してみましょう。
もう、pending になっているテストはないはずです。
$ scala -cp scalatest-1.5.jar org.scalatest.tools.Runner -p . -o -s
ExampleSuite
Run starting. Expected test count is: 2
ExampleSuite:
- pop を空でない stack で実施
- pop を空の stack で実施
Run completed in 73 milliseconds.
Total number of tests run: 2
Suites: completed 1, aborted 0
Tests: succeeded 2, failed 0, ignored 0, pending 0
All tests passed.