Using a HavePropertyMatcher for collection elements in ScalaTest?

I've been using ScalaTest's FeatureSpec for a couple of days now and I'm trying to understand if it's possible to define the following spec using the built-in matchers (and if not, how I can write a suitable custom matcher).

Suppose I have the class Book:

case class Book(val title: String, val author: String)

and in my test I have a List of books:

val books = List(Book("Moby Dick", "Melville"))

Now, I would like to specify that the books list should contain a book with the title "Moby Dick". I would like to write something like:

books should contain (value with title "Moby Dick")

I can't seem to figure out from the docs and code if it's possible to express this requirement in ScalaTest. Has anyone ran into a similar situation?


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
matchResults.find(_.matches) != None," and ")," 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.

Category:unit testing Time:2011-08-09 Views:1

Related post

  • When serializing a custom generic collection to Xml how do I add an attribute to the generated collection element 2009-09-17

    When serializing a custom generic collection to Xml how do I add an attribute to the generated collection element. Currently I have: <RootObject> <Id>1</Id> <Items> <MyCollectionItem/> <MyCollectionItem/> </Item

  • Joining tables in NHibernate gets "collection element mapping has wrong number of columns" 2011-07-05

    I'm having trouble mapping a many-to-many relationship with a join table. The errror message I am getting is "collection element mapping has wrong number of columns" My db schema is basically: . Despite the picture from SQL Server Management Studio,

  • gcroot Collection - element access 2011-09-19

    I'm making bridge from .NET to C++ and using Collection as a public element like this : gcroot<System::Collections::ObjectModel::Collection<BModel::Device ^> ^> Devices; I'm using gcroot because my c++ class is not managed (it's MFC) but

  • How can I rewrite my code to bind a collection element in code? 2012-01-26

    How can I write Binding from XAML in my code to bind my collection element? <GridViewColumn Width="70" DisplayMemberBinding="{Binding PageConfidences[0], StringFormat=p1}"> ... </GridViewColumn> --------------Solutions------------- Depend

  • Checking if a collection element exists in Oracle 2009-08-28

    I create a simple type: create or replace TYPE SIMPLE_TYPE AS OBJECT (ID NUMBER(38), NAME VARCHAR2(20)); Simple test: DECLARE TYPE ObjectList IS TABLE OF SIMPLE_TYPE; tmp SIMPLE_TYPE := SIMPLE_TYPE(1, 'a'); o ObjectList := new ObjectList(SIMPLE_TYPE(

  • Hibernate interceptor: entity intercepted when a collection element updated 2009-10-14

    I need to know how can I set Hibernate (...) to achieve the following issue: I have a bidirectional (composition) one-to-many association ( is a Set object and b.a is a A object). When I load "a" from DB and I update one of its "bs" I need Hierna

  • How to override xml element name for collection elements using XmlAttributeOverrides? 2010-02-11

    I've got a very basic object object model that is being serialized by the System.Xml.XmlSerialization stuff. I need to use the XmlAttributeOverrides functionality to set the xml element names for a collection of child elements. public class Foo{ publ

  • Validating collection elements in WPF 2010-05-28

    I would like to know how people are going about validating collections in WPF. Lets say for example that I have an observable collection of ViewModels that I am binding to the items source of a grid, and the user can add new rows to the grid and need

  • What's a good and functional way to swap collection elements in Scala? 2010-07-26

    In a project of mine one common use case keeps coming up. At some point I've got a sorted collection of some kind (List, Seq, etc... doesn't matter) and one element of this collection. What I want to do is to swap the given element with it's followin

  • removing java.util.Collection elements by multiple threads 2011-03-07

    In a multi-thread module, I don't care whether it is thread-safely writing over a java.util.Collection (e.g. java.util.Set) object. What it does is removing some independent elements by multiple threads, which may perform removal on the same element

  • JAXB UnMarshall Collection element order 2011-03-14

    lets say i have the following XML <?xml version="1.0" encoding="utf-8"?> <names> <name first="John" last="Doe"/> <name first="Jane" last="Doe"/> ... </names> This is my code: final JAXBContext context = JAXBContext.newIn

  • JAXB UnMarshall Collection element order - continued 2011-05-31

    I am aware that almost the same question has been asked before (here). Despite that there is one interesting answer, there is still a loose end (in the case of unmarshalling) that also seems to apply in our case. Here's our situation: we're parsing S

  • How to collect elements of a collection basing on a result of some method? 2011-06-02

    Suppose we have a list of values sorted according to some ordering. We also have a map of elements mapped to these values. We want to obtain a collection of elements from the map in the same order as their keys are in the list. A straightforward meth

  • How to use MVC3 remote validation on collection elements in a model? 2011-07-21

    I'm using the MVC3 remote validation feature rather happily until I came across a collection in the page that needs to be edited. On our view we are using a data grid like construct (collection bound to the appropriate edit view) for the editing of a

  • Issues with {RelativeSource PreviousData} when removing collection elements 2011-07-28

    I'm using the following (simplified) code to display an element in all the items in an ItemsControl except the first: <TheElement Visibility="{Binding RelativeSource={RelativeSource PreviousData}, Converter={StaticResource NullToVisibility}}/>

  • Separate select for each collection element - hibernate 2012-01-13

    I have a class workspace that contains a collection of sheets i.e. there is a one to many relationship between workspace and lists. A workspace may have a million lists. The problem is that when I access a single element of the sheets collection with

  • Bind property of collection element 2012-04-18

    I have a GUI and DataGrid element (C#, WPF). There I have 4 columns - name, value, timestamp and comment. As a data source I use a collection of elements of type Parameter, that has properties name, value, timestamp and comment. How can I create data

  • Jaxb unmarshalling: not getting my collection elements 2012-04-23

    I am new to Jaxb and this is my first time using it. I have an xml that I would like it to be translated into my existing objects. I succeeded with simple attributes and elements, however with collections I am getting empty collections back. I want t

  • collecting elements of word file for output 2013-10-08

    A couple of queries about collecting file elements in Word. 1. Where do I find a list of fonts used in a given file? 2. Is Word capable of collecting all elements (fonts, pics, graphics etc) used within a Word file? If so how do you do this? Reason:

Copyright (C), All Rights Reserved.

processed in 1.474 (s). 13 q(s)