Added ConcurrentModificationException test
This commit is contained in:
parent
c198a96ec5
commit
c40d6962dd
|
@ -0,0 +1,54 @@
|
|||
package com.baeldung.java.concurrentmodificationexception;
|
||||
|
||||
import org.assertj.core.api.Assertions;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.Iterator;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.util.Lists.newArrayList;
|
||||
|
||||
public class ConcurrentModificationUnitTest {
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whilstRemovingDuringIteration_shouldThrowException() throws InterruptedException {
|
||||
|
||||
ArrayList<Integer> integers = newArrayList(1, 2, 3);
|
||||
|
||||
for (Integer integer : integers) {
|
||||
integers.remove(1);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whilstRemovingDuringIteration_shouldNotThrowException() throws InterruptedException {
|
||||
|
||||
ArrayList<Integer> integers = newArrayList(1, 2, 3);
|
||||
|
||||
for (Iterator<Integer> iterator = integers.iterator(); iterator.hasNext();) {
|
||||
Integer integer = iterator.next();
|
||||
if(integer == 2) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(integers).containsExactly(1, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whilstRemovingDuringForEach_shouldNotThrowException() throws InterruptedException {
|
||||
|
||||
ArrayList<Integer> integers = newArrayList(1, 2, 3);
|
||||
ArrayList<Integer> toRemove = newArrayList();
|
||||
|
||||
for (Integer integer : integers) {
|
||||
if(integer == 2) {
|
||||
toRemove.add(integer);
|
||||
}
|
||||
}
|
||||
integers.removeAll(toRemove);
|
||||
|
||||
assertThat(integers).containsExactly(1, 3);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue