1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.collections4.iterators;
18
19 import static org.junit.jupiter.api.Assertions.assertFalse;
20 import static org.junit.jupiter.api.Assertions.assertNotNull;
21 import static org.junit.jupiter.api.Assertions.assertThrows;
22 import static org.junit.jupiter.api.Assertions.assertTrue;
23 import static org.junit.jupiter.api.Assertions.fail;
24
25 import java.util.Iterator;
26 import java.util.NoSuchElementException;
27
28 import org.apache.commons.collections4.AbstractObjectTest;
29 import org.junit.jupiter.api.Test;
30
31
32
33
34
35
36
37
38
39 public abstract class AbstractIteratorTest<E> extends AbstractObjectTest {
40
41
42
43
44
45
46 public AbstractIteratorTest(final String testName) {
47 super(testName);
48 }
49
50
51
52
53
54
55 public abstract Iterator<E> makeEmptyIterator();
56
57
58
59
60
61
62 @Override
63 public abstract Iterator<E> makeObject();
64
65
66
67
68
69
70
71 public boolean supportsEmptyIterator() {
72 return true;
73 }
74
75
76
77
78
79
80
81 public boolean supportsFullIterator() {
82 return true;
83 }
84
85
86
87
88
89
90
91 public boolean supportsRemove() {
92 return true;
93 }
94
95
96
97
98 @Test
99 public void testEmptyIterator() {
100 if (!supportsEmptyIterator()) {
101 return;
102 }
103
104 final Iterator<E> it = makeEmptyIterator();
105
106
107 assertFalse(it.hasNext(), "hasNext() should return false for empty iterators");
108
109
110 assertThrows(NoSuchElementException.class, () -> it.next(),
111 "NoSuchElementException must be thrown when Iterator is exhausted");
112 verify();
113
114 assertNotNull(it.toString());
115 }
116
117
118
119
120 @Test
121 public void testFullIterator() {
122 if (!supportsFullIterator()) {
123 return;
124 }
125
126 final Iterator<E> it = makeObject();
127
128
129 assertTrue(it.hasNext(), "hasNext() should return true for at least one element");
130
131
132 try {
133 it.next();
134 } catch (final NoSuchElementException e) {
135 fail("Full iterators must have at least one element");
136 }
137
138
139 while (it.hasNext()) {
140 it.next();
141 verify();
142 }
143
144
145 assertThrows(NoSuchElementException.class, () -> it.next(),
146 "NoSuchElementException must be thrown when Iterator is exhausted");
147
148 assertNotNull(it.toString());
149 }
150
151
152
153
154 @Test
155 public void testRemove() {
156 final Iterator<E> it = makeObject();
157
158 if (!supportsRemove()) {
159
160 try {
161 it.remove();
162 } catch (final UnsupportedOperationException ex) {}
163 return;
164 }
165
166
167 assertThrows(IllegalStateException.class, () -> it.remove());
168 verify();
169
170
171 it.next();
172 it.remove();
173
174
175 assertThrows(IllegalStateException.class, () -> it.remove());
176 }
177
178
179
180
181 public void verify() {
182
183 }
184
185 }