1

I want to assert (using JUnit and not any other dependencies like hamcrest) if a collection contains an element with a certain property value).

I found this question How do I assert an Iterable contains elements with a certain property? using harmcrest.

One option is to override the equals method to check only the property that I want to compare, but it is not a good solution.

Is there an elegant way to make this using JUnit 4 or should I code it and iterate through the collection to check the value?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
dhalfageme
  • 1,444
  • 4
  • 21
  • 42

1 Answers1

1

Java 8's streams and filtering could actually be quite elegant:

Collection<SomeObejct> myCollection = /* something */;
boolean hasAny = myCollection.stream().anyMatch(s -> s.getProperty().equals("something"));
assertTrue("Couldn't find an object with the right property", hasAny);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    It works! Thanks!. Another question. Do you know why in my case I should provide the assert argument in different order (first the asser error message and the condition tested in the second place). MAybe is related to this other question with my project setup https://stackoverflow.com/questions/60776770/java-maven-eclipse-junit-package-not-found – dhalfageme Mar 21 '20 at 12:20
  • @dhalfageme Sorry, that was my mistake. I'm used to JUnit 5 Jupiter, which has the message as the last argument. In JUnit 4, the message is in indeed the first argument. I've edited my answer accordingly. – Mureinik Mar 21 '20 at 12:24