jiopaley
jiopaley

Reputation: 146

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

Upvotes: 2

Views: 4625

Answers (3)

Wajih
Wajih

Reputation: 925

to verify/assert/test that listOfMyData contains MyData with 4 as the value of the .two attribute, you can either filter the elements which match your filter function here (.two==4) and then test the length of the filtered list/seq

listOfMyData.filter(_.two==4).length > 0

or better use find to find the first match (which returns an Optionp[MyData])

listOfMyData.find(_.two==4) != None

with FunSuite and with/without Matchers

class MyDataTestSuite extends FunSuite  with Matchers {

  test("test") {
    case class MyData(one: Int, two: Int)
    val listOfMyData = List(new MyData(1,2), new MyData(3,4))
    listOfMyData.find(_.two==4) should not be None
    // equivalent to
    assert(listOfMyData.find(_.two==4) != None)
  }
}

Upvotes: 0

Dima
Dima

Reputation: 40508

How about this list.map(_.two) should contain (4)

You can also do atLeast(1, dataList) should matchPattern MyData(_, 4)

Upvotes: 3

prayagupadhyay
prayagupadhyay

Reputation: 31262

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))

Upvotes: 2

Related Questions