1+ package com .baeldung .hamcrest .listcontainitems ;
2+
3+ import org .junit .jupiter .api .Test ;
4+
5+ import java .util .List ;
6+
7+ import static org .hamcrest .MatcherAssert .assertThat ;
8+ import static org .hamcrest .Matchers .*;
9+ import static org .junit .jupiter .api .Assertions .assertTrue ;
10+
11+
12+ public class HamcrestElementPropInCollectionUnitTest {
13+ private static final List <Developer > DEVELOPERS = List .of (
14+ new Developer ("Kai" , 28 , "Linux" , List .of ("Kotlin" , "Python" )),
15+ new Developer ("Liam" , 26 , "MacOS" , List .of ("Java" , "C#" )),
16+ new Developer ("Kevin" , 24 , "MacOS" , List .of ("Python" , "Go" )),
17+ new Developer ("Saajan" , 22 , "MacOS" , List .of ("Ruby" , "Php" , "Typescript" )),
18+ new Developer ("Eric" , 27 , "Linux" , List .of ("Java" , "C" ))
19+ );
20+
21+ @ Test
22+ void whenUsingHamcrestMatchers_thenCorrect () {
23+ assertThat (DEVELOPERS , hasItem (hasProperty ("os" , equalTo ("Linux" ))));
24+ assertThat (DEVELOPERS , hasItem (hasProperty ("name" , is ("Kai" ))));
25+ assertThat (DEVELOPERS , hasItem (hasProperty ("age" , lessThan (28 ))));
26+ assertThat (DEVELOPERS , hasItem (hasProperty ("languages" , hasItem ("Go" ))));
27+
28+ assertThat (DEVELOPERS , hasItem (
29+ anyOf (
30+ hasProperty ("languages" , hasItem ("C" )),
31+ hasProperty ("os" , is ("Windows" ))) // <-- No dev has the OS "Windows"
32+ ));
33+
34+ assertThat (DEVELOPERS , hasItem (
35+ allOf (
36+ hasProperty ("languages" , hasItem ("C" )),
37+ hasProperty ("os" , is ("Linux" )),
38+ hasProperty ("age" , greaterThan (25 )))
39+ ));
40+
41+ assertThat (DEVELOPERS , not (hasItem ( // <-- not() matcher
42+ allOf (
43+ hasProperty ("languages" , hasItem ("C#" )),
44+ hasProperty ("os" , is ("Linux" )),
45+ hasProperty ("age" , greaterThan (25 )))
46+ )));
47+ }
48+
49+ @ Test
50+ void whenUsingStreamAnyMatch_thenCorrect () {
51+ assertTrue (DEVELOPERS .stream ().anyMatch (dev -> dev .getOs ().equals ("Linux" )));
52+ assertTrue (DEVELOPERS .stream ().anyMatch (dev -> dev .getAge () < 28 ));
53+ assertTrue (DEVELOPERS .stream ().anyMatch (dev -> dev .getLanguages ().contains ("Go" )));
54+ assertTrue (DEVELOPERS .stream ().anyMatch (dev -> dev .getLanguages ().contains ("C" ) && dev .getOs ().equals ("Linux" )));
55+ }
56+
57+ }
0 commit comments