8

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?

Alex Vayda
  • 6,154
  • 5
  • 34
  • 50
  • Found a very similar question here - http://stackoverflow.com/questions/6997939/using-a-havepropertymatcher-for-collection-elements-in-scalatest – Alex Vayda Sep 20 '14 at 00:28

2 Answers2

7

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.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • Forgot to mention in the question - I want to do it with a single matching expression. In other words I need to have a Matcher instance that does this check. It's easy to achieve it with two `should`, but how would I combine them in one? – Alex Vayda Sep 19 '14 at 23:46
  • 1
    Why would you do that? Check each assertion independently. – Jean Logeart Sep 19 '14 at 23:48
  • The second check does what you want: if the list only contains books that are in 2014, then it is not empty. – Jean Logeart Sep 19 '14 at 23:49
  • I want to compose a single Matcher that would inspect a given collection in all the different ways. Non-empty check is just an example. The idea is to find a way how to compose matchers via `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 – Alex Vayda Sep 20 '14 at 00:07
  • 1
    Maybe a custom matcher is what you are after? http://www.scalatest.org/user_guide/using_matchers#usingCustomMatchers – Kulu Limpa Sep 20 '14 at 00:22
  • Seems so. Just thought it would possible with standard matchers. Apparently not. – Alex Vayda Sep 20 '14 at 00:25
  • Isn't composition of matchers (manual: http://www.scalatest.org/user_guide/using_matchers#creatingMatchersUsingLogicalOperators ) what you're looking for? – tilois Sep 20 '14 at 11:50
0

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
senjin.hajrulahovic
  • 2,961
  • 2
  • 17
  • 32