Search code examples
scalascalatest

How do I use scala and scalatest to see if a list contains an object with a field matching a specific value


I would like my test to check that a list of object contains an object with a specific matching field. For example:

class ListTest extends ScalaTesting {
    class MyData(val one:Int, val two:Int) {
    }

    val listOfMyData = List(new MyData(1,2), new MyData(3,4)

    listOfMyData should contain (a mydata object with field two matching 4)
}

Obviously this doesn't actually work


Solution

  • Whenever i have to assert fields of list, I do .map over the list and compare the value.

    eg.

    class SomeSpecs extends FunSuite with Matchers {
    
      test("contains values") {
    
        case class MyData(field1: Int, field2: Int)
    
        List(new MyData(1,2), new MyData(3,4)).map(_.field2) should contain (4)
      }
    }
    

    And List(new MyData(1,2), new MyData(3,9)).map(_.field2) should contain (4) will throw error List(2, 9) did not contain element 4.

    The second approach would be

    List(new MyData(1, 2), new MyData(3, 9)).count(_.field2 == 4) > 0 shouldBe true
    // or
    List(new MyData(1, 2), new MyData(3, 4)).count(_.field2 == 4) should be > 0
    

    but the thing I don't like about this is its true or false. eg. List(new MyData(1, 2), new MyData(3, 11)).count(_.field2 == 4) shouldBe true throws error false was not equal to true

    while the first approach tells me more than that as it gives what is the input data and what is expected. At least I find first approach helpful while refactoring tests.

    Third approach can be

    List(new MyData(1, 9), new MyData(3, 4)).filter(_.field2 == 4) should not be empty
    

    But I WISH scalatest also had something like List(new MyData(1,2), new MyData(3,4)) should contain (MyData(_, 4))