Search code examples
javajunitassertj

AssertJ: A way to check for an object's field value if it contains a particular pattern (regex)


Hi Java Gurus and AssertJ Gurus,

I would like to ask if there is a way in AssertJ to verify if an object exists from a list of Objects (e.g. ArrayList<TestObject> listOfTestObjects). Where that particular object's field (getter method's return) value matches a pattern or regular expression pattern.

Please see example below for more details:

class TestObject {
    private String stringValue;

    public String getValue() {
       return this.stringValue;
    }
    public void setValue(String newStringValue) {
        this.stringValue = newStringValue;
    }

}

ArrayList<TestObject> listOfTestObjects = new ArrayList<TestObject>();

// populate the list here...

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

Please take note that I am not expecting "

...containsAnElementWith("some regular expressions here...");"

to be an existing method (which can actually be better if there is) but this can be a feature(s)/method(s) in assertj or junit that I can use to simplify unit test automation other than looping through one of them then doing a match.


Cheers


Solution

  • assertThat(listOfTestObjects).anyMatch(o -> o.getValue().matches(regex));
    

    http://joel-costigliola.github.io/assertj/core-8/api/org/assertj/core/api/AbstractIterableAssert.html#anyMatch-java.util.function.Predicate-