File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed
core-java-modules/core-java-collections-6/src
main/java/com/baeldung/checkedcollections
test/java/com/baeldung/checkedcollections Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .baeldung .checkedcollections ;
2+
3+ import java .util .Collection ;
4+
5+ class DataProcessor {
6+
7+ public boolean checkPrefix (Collection <?> data ) {
8+ boolean result = true ;
9+ if (data != null ) {
10+ for (Object item : data ) {
11+ if (item != null && !((String ) item ).startsWith ("DATA_" )) {
12+ result = false ;
13+ break ;
14+ }
15+ }
16+ }
17+ return result ;
18+ }
19+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .checkedcollections ;
2+
3+ import static org .junit .jupiter .api .Assertions .assertThrows ;
4+ import static org .junit .jupiter .api .Assertions .assertTrue ;
5+
6+ import java .util .ArrayList ;
7+ import java .util .Collection ;
8+ import java .util .Collections ;
9+
10+ import org .junit .jupiter .api .Test ;
11+
12+ class DataProcessorUnitTest {
13+
14+ @ Test
15+ void givenGenericCollection_whenInvalidTypeDataAdded_thenFailsAfterInvocation () {
16+ Collection data = new ArrayList <>();
17+ data .add ("DATA_ONE" );
18+ data .add ("DATA_TWO" );
19+ data .add (3 ); // should have failed here
20+
21+ DataProcessor dataProcessor = new DataProcessor ();
22+
23+ assertThrows (ClassCastException .class , () -> dataProcessor .checkPrefix (data )); // but fails here
24+ }
25+
26+ @ Test
27+ void givenGenericCollection_whenInvalidTypeDataAdded_thenFailsAfterAdding () {
28+ Collection data = Collections .checkedCollection (new ArrayList <>(), String .class );
29+ data .add ("DATA_ONE" );
30+ data .add ("DATA_TWO" );
31+
32+ assertThrows (ClassCastException .class , () -> {
33+ data .add (3 ); // fails here
34+ });
35+
36+ DataProcessor dataProcessor = new DataProcessor ();
37+ final boolean result = dataProcessor .checkPrefix (data );
38+ assertTrue (result );
39+
40+ }
41+ }
You can’t perform that action at this time.
0 commit comments