1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.collections4.bag;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertFalse;
21 import static org.junit.jupiter.api.Assertions.assertThrows;
22 import static org.junit.jupiter.api.Assertions.assertTrue;
23
24 import java.util.Set;
25
26 import org.apache.commons.collections4.Bag;
27 import org.apache.commons.collections4.Predicate;
28 import org.apache.commons.collections4.functors.TruePredicate;
29 import org.junit.jupiter.api.Test;
30
31
32
33
34
35 public class PredicatedBagTest<T> extends AbstractBagTest<T> {
36
37 protected Predicate<T> truePredicate = TruePredicate.<T>truePredicate();
38
39 protected Bag<T> decorateBag(final HashBag<T> bag, final Predicate<T> predicate) {
40 return PredicatedBag.predicatedBag(bag, predicate);
41 }
42
43 @Override
44 public String getCompatibilityVersion() {
45 return "4";
46 }
47
48 @Override
49 protected int getIterationBehaviour() {
50 return UNORDERED;
51 }
52
53 @Override
54 public Bag<T> makeObject() {
55 return decorateBag(new HashBag<>(), truePredicate);
56 }
57
58 protected Bag<T> makeTestBag() {
59 return decorateBag(new HashBag<>(), stringPredicate());
60 }
61
62 protected Predicate<T> stringPredicate() {
63 return String.class::isInstance;
64 }
65
66 @Test
67 @SuppressWarnings("unchecked")
68 public void testIllegalAdd() {
69 final Bag<T> bag = makeTestBag();
70 final Integer i = 3;
71
72 assertThrows(IllegalArgumentException.class, () -> bag.add((T) i));
73
74 assertFalse(bag.contains(i), "Collection shouldn't contain illegal element");
75 }
76
77 @Test
78 @SuppressWarnings("unchecked")
79 public void testIllegalDecorate() {
80 final HashBag<Object> elements = new HashBag<>();
81 elements.add("one");
82 elements.add("two");
83 elements.add(3);
84 elements.add("four");
85
86 assertThrows(IllegalArgumentException.class, () -> decorateBag((HashBag<T>) elements, stringPredicate()));
87
88 assertThrows(NullPointerException.class, () -> decorateBag(new HashBag<>(), null));
89 }
90
91 @Test
92 @SuppressWarnings("unchecked")
93 public void testLegalAddRemove() {
94 final Bag<T> bag = makeTestBag();
95 assertEquals(0, bag.size());
96 final T[] els = (T[]) new Object[] { "1", "3", "5", "7", "2", "4", "1" };
97 for (int i = 0; i < els.length; i++) {
98 bag.add(els[i]);
99 assertEquals(i + 1, bag.size());
100 assertTrue(bag.contains(els[i]));
101 }
102 Set<T> set = bag.uniqueSet();
103 assertTrue(set.contains(els[0]), "Unique set contains the first element");
104 assertTrue(bag.remove(els[0]));
105 set = bag.uniqueSet();
106 assertFalse(set.contains(els[0]), "Unique set now does not contain the first element");
107 }
108
109
110
111
112
113
114
115
116 }