Matchers in scalatest
scalatestでは a should be (b)のように、「検査対象の値が〜であること」(この例では「aはbであること」)という書き方をする。
「〜である」を指定する方法(Matcherと呼ぶ)がいくつかあるので簡単にまとめてみる
be の後の()の中に期待値を書く。
name should be ("scala")be の代わりに equal も使える。
name should equal ("scala")be と equalは、特に機能的な違いはないので、テスト記述の文脈的にあっている方を使えば良い。1 :: 2 :: Nil should equal (List(1,2))"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)
retrievedResult should be theSameInstanceAs(cachedResult)
be, equal で判定できるが、それ以外にも下記のような判定機能もあるval aList = List(.......)
aList should contain(anElement)
aList should have length(9)
aList should have size(9)
val aMap = Map(.........)
aMap should contain key ("aKeyName")
aMap should contain value ("aValue")
adult.age should not be < (20)
newMultiParadigmLanguage should (contain "object-oriented" and contain "functional")
yoshiIkuzoVillage should not (contain "television" or contain "radio")
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")
interceptで、スローされる例外の型を指定する。IllegalArgumentExceptionがスローされないとテストはfailするintercept[IllegalArgumentException] {
Age(-24)
}
exceptionの内容のテストする場合は、例外をevaluatingで受け取り、produceで型をチェックしたりできる val thrownException = evaluating {
Age(-24)
} must produce [IllegalArgumentException]
thrownException.getMessage() must include ("invalid age")