Assertj-core: How to check if a list of objects has an element with a String property matching a regex pattern

Created on 26 Nov 2019  路  2Comments  路  Source: assertj/assertj-core

Summary

Given a list of objects with a String field or getter method returning a String, is there a way in assertj to check if out from the list an object contains a string based from a "Regular Expression Pattern"?

Kindly see example below for more details.

Example

class MyObject {
    private String theValue;

    public String getValue() {
       return theValue;
    }
    public void setValue(String newValue) {
        this.theValue = newValue;
    }

}

List<MyObject> listOfMyObjects = new ArrayList<MyObject>();

// populate the list here...

assertThat(listOfMyObjects).extracting("value").containsAnElementWith("some regular expressions here...");

question

Most helpful comment

You could use extracting(Function) together with anyMatch or anySatisfy:

MyObject foo = new MyObject();
foo.setValue("foo");
MyObject aaa = new MyObject();
aaa.setValue("aaa");
List<MyObject> listOfMyObjects = Arrays.asList(foo, aaa);

assertThat(listOfMyObjects)
  .extracting(MyObject::getValue)
  .anyMatch(value -> value.matches("a*")) // shorter with java.lang.String#matches
  .anySatisfy(value -> assertThat(value).matches("a*")); // nicer error message with StringAssert

All 2 comments

You could use extracting(Function) together with anyMatch or anySatisfy:

MyObject foo = new MyObject();
foo.setValue("foo");
MyObject aaa = new MyObject();
aaa.setValue("aaa");
List<MyObject> listOfMyObjects = Arrays.asList(foo, aaa);

assertThat(listOfMyObjects)
  .extracting(MyObject::getValue)
  .anyMatch(value -> value.matches("a*")) // shorter with java.lang.String#matches
  .anySatisfy(value -> assertThat(value).matches("a*")); // nicer error message with StringAssert

@laskybontiagmail I'm closing the issue, feel free to comment if you need more help and we will reopne it.

Was this page helpful?
0 / 5 - 0 ratings