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?
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?
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.
should
, but how would I combine them in one? –
Nolie and
and or
having one matcher to check the collection properties (e.g. collection size) while another matcher checks collection element. I tried to use have
matcher in this way - book should (have size 1 and contain(have (...)))
, but that didn't work –
Nolie There is a purposely built scalatest
class called LoneElement
:
https://www.scalatest.org/scaladoc/3.0.8/org/scalatest/LoneElement.html
import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper
books.loneElement.year shouldBe 2014
© 2022 - 2024 — McMap. All rights reserved.