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

2

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?

Nolie answered 19/9, 2014 at 23:26 Comment(1)
Found a very similar question here - #6998439Nolie
R
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.

Raney answered 19/9, 2014 at 23:37 Comment(7)
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?Nolie
Why would you do that? Check each assertion independently.Raney
The second check does what you want: if the list only contains books that are in 2014, then it is not empty.Raney
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 workNolie
Maybe a custom matcher is what you are after? scalatest.org/user_guide/using_matchers#usingCustomMatchersFibrosis
Seems so. Just thought it would possible with standard matchers. Apparently not.Nolie
Isn't composition of matchers (manual: scalatest.org/user_guide/… ) what you're looking for?Marijo
C
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
Countrydance answered 9/6, 2023 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.