Using a HavePropertyMatcher for collection elements in ScalaTest?

北城余情 提交于 2019-12-04 08:36:12

Not currently, though you will be able to do something like this very soon in the future. What you can do now is something like:

books.exists(_.title == "Moby Dick") should be (true)

In the meantime here's a custom matcher you can use:

def containElement[T](right: Matcher[T]) = new Matcher[Seq[T]] {
  def apply(left: Seq[T]) = {
    val matchResults = left map right
    MatchResult(
      matchResults.find(_.matches) != None,
      matchResults.map(_.failureMessage).mkString(" and "),
      matchResults.map(_.negatedFailureMessage).mkString(" and ")
    )
  }
}

Then you can use the full power of the ScalaTest Have matcher to inspect the fields of your object:

val books = List(Book("Moby Dick", "Melville"),
                 Book("Billy Budd", "Melville"), 
                 Book("War and Peace", "Tolstoy"))

books should containElement(have('title("Moby Dick")))
books should containElement(have('title("Billy Budd"), 'author("Melville")))
books should containElement(have('title("War and Peace"), 'author("Melville")))

The last one is a failure producing this output:

The title property had value "Moby Dick", instead of its expected value "War and Peace", on object Book(Moby Dick,Melville) and The title property had value "Billy Budd", instead of its expected value "War and Peace", on object Book(Billy Budd,Melville) and The author property had value "Tolstoy", instead of its expected value "Melville", on object Book(War and Peace,Tolstoy)

You can also combine matchers with and or or, use not, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!