scalascalatestmatcher

Scalatest: how to check if a collection contains element that satisfies certain criteria


Say I have a list of books:

val books = List(
    Book(title="Foo", year=2014),
    Book(title="Bar", year=2014))

How to check with a single expression if collection books is not empty and only contains books published in 2014?


Solution

  • Using matchers:

    books should not be empty
    books.map(_.year) should contain only (2014)
    

    Or just:

    books.map(_.year) should contain only (2014)
    

    since this check asserts that the list is not empty.