scalatestでは a should be (b)
のように、「検査対象の値が〜であること」(この例では「a
はb
であること」)という書き方をする。
「〜である」を指定する方法(Matcherと呼ぶ)がいくつかあるので簡単にまとめてみる
- 上記の例のように
be
の後の()の中に期待値を書く。name should be ("scala")
be
の代わりにequal
も使える。name should equal ("scala")
be
とequal
は、特に機能的な違いはないので、テスト記述の文脈的にあっている方を使えば良い。- objectの等価性も判定できる。
1 :: 2 :: Nil should equal (List(1,2))
- scala言語における等価性(何をもって同じとみなすか)については、英語ですがこちらを参照。
- 前方一致、後方一致、部分一致
"scalatest" should startWith ("scala")
"scalatest" should endWith ("est")
"scalatest" should include ("late")
- さらに正規表現と組み合わせることもできる
"testing in scala" should startWith regex ("[e,s,t]+")
"testing in scala" should endWith regex ("[a,l]+")
- 正規表現に文字列全体がマッチするか判定する場合は下記
"testing in scala" should fullyMatch regex ("test.*scala")
adultAge should be >= (20)
ageElementary1st should be === (6)
oyatsuBudget should be < (300)
-
等号は
===
と書くことになってる -
浮動小数点数の誤差許容範囲
(0.9 - 0.8) should be (0.1 plusOrMinus .01)
- objectの参照先が同じインスタンスかどうかを判定
retrievedResult should be theSameInstanceAs(cachedResult)
- Collection全体の等価性は、
be
,equal
で判定できるが、それ以外にも下記のような判定機能もある
val aList = List(.......)
aList should contain(anElement)
aList should have length(9)
aList should have size(9)
- java.util.Collectionでも使える
val aMap = Map(.........)
aMap should contain key ("aKeyName")
aMap should contain value ("aValue")
- java.util.Mapでも使える
- and/or, notで条件を組み合わせる
adult.age should not be < (20)
newMultiParadigmLanguage should (contain "object-oriented" and contain "functional")
yoshiIkuzoVillage should not (contain "television" or contain "radio")
- getterを使って取得した値の等価性を判定する
- ここでいうpropertyは ScalaCheckなどの property based testingでいうところのpropertyではなく、JavaでいうBean Propertyのこと
val person = Engineer("taro", "yamada", 1990, Department("dev.1"))
person should have (
'firstName ("taro")
'lastName ("yamada")
'birth (1980),
'department (Department("dev.1"))
)
- 残念ながら
person should have 'age > (20)
のような書き方はできない。等価性判定のみである
"using null" must not be ("scala")
- shouldと機能的な違いはないので、文脈によって使い分けるものらしい
intercept
で、スローされる例外の型を指定する。- この例の場合、
IllegalArgumentException
がスローされないとテストはfailする
intercept[IllegalArgumentException] {
Age(-24)
}
exception
の内容のテストする場合は、例外をevaluating
で受け取り、produce
で型をチェックしたりできる
val thrownException = evaluating {
Age(-24)
} must produce [IllegalArgumentException]
thrownException.getMessage() must include ("invalid age")