Skip to content

Instantly share code, notes, and snippets.

@ryo-murai
Last active February 24, 2021 02:13
Show Gist options
  • Save ryo-murai/5260404 to your computer and use it in GitHub Desktop.
Save ryo-murai/5260404 to your computer and use it in GitHub Desktop.
Matchers in scalatest

Matchers in scalatest

scalatestでは a should be (b)のように、「検査対象の値が〜であること」(この例では「abであること」)という書き方をする。 「〜である」を指定する方法(Matcherと呼ぶ)がいくつかあるので簡単にまとめてみる

等価性(equality)

  • 上記の例のように be の後の()の中に期待値を書く。 name should be ("scala")
  • be の代わりに equal も使える。 name should equal ("scala")
  • beequalは、特に機能的な違いはないので、テスト記述の文脈的にあっている方を使えば良い。
  • 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等価性(equality)

  • objectの参照先が同じインスタンスかどうかを判定
retrievedResult should be theSameInstanceAs(cachedResult)

Collectionの判定

  • Collection全体の等価性は、be, equal で判定できるが、それ以外にも下記のような判定機能もある
val aList = List(.......)
aList should contain(anElement)
aList should have length(9)
aList should have size(9)
  • java.util.Collectionでも使える

Mapの判定

val aMap = Map(.........)
aMap should contain key ("aKeyName")
aMap should contain value ("aValue")
  • java.util.Mapでも使える

and/or, not

  • 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")

object property の判定

  • 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) のような書き方はできない。等価性判定のみである

must

"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")

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment