diff --git a/src/main/java/org/apache/commons/collections4/list/SetUniqueList.java b/src/main/java/org/apache/commons/collections4/list/SetUniqueList.java index ce547ab531..225d4b3364 100644 --- a/src/main/java/org/apache/commons/collections4/list/SetUniqueList.java +++ b/src/main/java/org/apache/commons/collections4/list/SetUniqueList.java @@ -146,6 +146,7 @@ public boolean add(final E object) { */ @Override public void add(final int index, final E object) { + checkInterval(index, 0, size()); // adds element if it is not contained already if (set.contains(object) == false) { set.add(object); @@ -429,5 +430,17 @@ public void set(final E object) { throw new UnsupportedOperationException("ListIterator does not support set"); } } - + /** + * Checks whether the index is valid. + * + * @param index the index to check + * @param startIndex the first allowed index + * @param endIndex the last allowed index + * @throws IndexOutOfBoundsException if the index is invalid + */ + private void checkInterval(final int index, final int startIndex, final int endIndex) { + if (index < startIndex || index > endIndex) { + throw new IndexOutOfBoundsException("Invalid index:" + index + ", size=" + size()); + } + } } diff --git a/src/test/java/org/apache/commons/collections4/AbstractArrayListTest.java b/src/test/java/org/apache/commons/collections4/AbstractArrayListTest.java index a067251b63..9ad4b5e6b3 100644 --- a/src/test/java/org/apache/commons/collections4/AbstractArrayListTest.java +++ b/src/test/java/org/apache/commons/collections4/AbstractArrayListTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import org.apache.commons.collections4.list.AbstractListTest; @@ -42,11 +47,14 @@ public void testNewArrayList() { assertTrue("New list is empty", list.isEmpty()); assertEquals("New list has size zero", 0, list.size()); - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(1); - fail("get(int i) should have thrown IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException e) { - // Expected result + }); + String actualMessage = exception.getMessage(); + if (null == actualMessage) { + assertNull(actualMessage); + } else { + assertNotNull(actualMessage); } } diff --git a/src/test/java/org/apache/commons/collections4/AbstractLinkedListTest.java b/src/test/java/org/apache/commons/collections4/AbstractLinkedListTest.java index acaf9dc85f..6a521a1aab 100644 --- a/src/test/java/org/apache/commons/collections4/AbstractLinkedListTest.java +++ b/src/test/java/org/apache/commons/collections4/AbstractLinkedListTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; @@ -110,13 +113,10 @@ public void testLinkedListAddLast() { */ public void testLinkedListGetFirst() { resetEmpty(); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { getCollection().getFirst(); - fail("getFirst() should throw a NoSuchElementException for an " + - "empty list."); - } catch (final NoSuchElementException e) { - // This is correct - } + }); + assertNull(exception.getMessage()); verify(); resetFull(); @@ -132,13 +132,10 @@ public void testLinkedListGetFirst() { */ public void testLinkedListGetLast() { resetEmpty(); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { getCollection().getLast(); - fail("getLast() should throw a NoSuchElementException for an " + - "empty list."); - } catch (final NoSuchElementException e) { - // This is correct - } + }); + assertNull(exception.getMessage()); verify(); resetFull(); @@ -158,13 +155,10 @@ public void testLinkedListRemoveFirst() { } resetEmpty(); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { getCollection().removeFirst(); - fail("removeFirst() should throw a NoSuchElementException for " + - "an empty list."); - } catch (final NoSuchElementException e) { - // This is correct - } + }); + assertNull(exception.getMessage()); verify(); resetFull(); @@ -184,13 +178,10 @@ public void testLinkedListRemoveLast() { } resetEmpty(); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { getCollection().removeLast(); - fail("removeLast() should throw a NoSuchElementException for " + - "an empty list."); - } catch (final NoSuchElementException e) { - // This is correct - } + }); + assertNull(exception.getMessage()); verify(); resetFull(); diff --git a/src/test/java/org/apache/commons/collections4/ArrayStackTest.java b/src/test/java/org/apache/commons/collections4/ArrayStackTest.java index 845915bd4f..9a75b75013 100644 --- a/src/test/java/org/apache/commons/collections4/ArrayStackTest.java +++ b/src/test/java/org/apache/commons/collections4/ArrayStackTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.util.EmptyStackException; import junit.framework.Test; @@ -46,20 +49,15 @@ public void testNewStack() { assertTrue("New stack is empty", stack.empty()); assertEquals("New stack has size zero", 0, stack.size()); - try { + Exception exception = assertThrows(EmptyStackException.class, () -> { stack.peek(); - fail("peek() should have thrown EmptyStackException"); - } catch (final EmptyStackException e) { - // Expected result - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(EmptyStackException.class, () -> { stack.pop(); - fail("pop() should have thrown EmptyStackException"); - } catch (final EmptyStackException e) { - // Expected result - } - + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") diff --git a/src/test/java/org/apache/commons/collections4/BagUtilsTest.java b/src/test/java/org/apache/commons/collections4/BagUtilsTest.java index 803832fbb3..8a1c201129 100644 --- a/src/test/java/org/apache/commons/collections4/BagUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/BagUtilsTest.java @@ -16,7 +16,9 @@ */ package org.apache.commons.collections4; -import static org.junit.Assert.*; +import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.commons.collections4.bag.HashBag; import org.apache.commons.collections4.bag.PredicatedBag; @@ -45,27 +47,23 @@ public class BagUtilsTest { @Test public void testSynchronizedBag() { final Bag bag = BagUtils.synchronizedBag(new HashBag<>()); - assertTrue("Returned object should be a SynchronizedBag.", - bag instanceof SynchronizedBag); - try { + assertTrue(bag instanceof SynchronizedBag); + Exception exception = assertThrows(NullPointerException.class, () -> { BagUtils.synchronizedBag(null); - fail("Expecting NullPointerException for null bag."); - } catch (final NullPointerException ex) { - // expected - } + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("collection")); } @Test public void testUnmodifiableBag() { final Bag bag = BagUtils.unmodifiableBag(new HashBag<>()); - assertTrue("Returned object should be an UnmodifiableBag.", - bag instanceof UnmodifiableBag); - try { + assertTrue(bag instanceof UnmodifiableBag); + Exception exception = assertThrows(NullPointerException.class, () -> { BagUtils.unmodifiableBag(null); - fail("Expecting NullPointerException for null bag."); - } catch (final NullPointerException ex) { - // expected - } + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("collection")); assertSame("UnmodifiableBag shall not be decorated", bag, BagUtils.unmodifiableBag(bag)); } @@ -73,65 +71,57 @@ public void testUnmodifiableBag() { @Test public void testPredicatedBag() { final Bag bag = BagUtils.predicatedBag(new HashBag<>(), truePredicate); - assertTrue("Returned object should be a PredicatedBag.", - bag instanceof PredicatedBag); - try { + assertTrue(bag instanceof PredicatedBag); + Exception exception = assertThrows(NullPointerException.class, () -> { BagUtils.predicatedBag(null, truePredicate); - fail("Expecting NullPointerException for null bag."); - } catch (final NullPointerException ex) { - // expected - } - try { + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("collection")); + + exception = assertThrows(NullPointerException.class, () -> { BagUtils.predicatedBag(new HashBag<>(), null); - fail("Expecting NullPointerException for null predicate."); - } catch (final NullPointerException ex) { - // expected - } + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("predicate")); } @Test public void testTransformedBag() { final Bag bag = BagUtils.transformingBag(new HashBag<>(), nopTransformer); - assertTrue("Returned object should be an TransformedBag.", - bag instanceof TransformedBag); - try { + assertTrue(bag instanceof TransformedBag); + Exception exception = assertThrows(NullPointerException.class, () -> { BagUtils.transformingBag(null, nopTransformer); - fail("Expecting NullPointerException for null bag."); - } catch (final NullPointerException ex) { - // expected - } - try { + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("collection")); + + exception = assertThrows(NullPointerException.class, () -> { BagUtils.transformingBag(new HashBag<>(), null); - fail("Expecting NullPointerException for null transformer."); - } catch (final NullPointerException ex) { - // expected - } + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("transformer")); } @Test public void testSynchronizedSortedBag() { final Bag bag = BagUtils.synchronizedSortedBag(new TreeBag<>()); - assertTrue("Returned object should be a SynchronizedSortedBag.", - bag instanceof SynchronizedSortedBag); - try { + assertTrue(bag instanceof SynchronizedSortedBag); + Exception exception = assertThrows(NullPointerException.class, () -> { BagUtils.synchronizedSortedBag(null); - fail("Expecting NullPointerException for null bag."); - } catch (final NullPointerException ex) { - // expected - } + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("collection")); } @Test public void testUnmodifiableSortedBag() { final SortedBag bag = BagUtils.unmodifiableSortedBag(new TreeBag<>()); - assertTrue("Returned object should be an UnmodifiableSortedBag.", - bag instanceof UnmodifiableSortedBag); - try { + assertTrue(bag instanceof UnmodifiableSortedBag); + Exception exception = assertThrows(NullPointerException.class, () -> { BagUtils.unmodifiableSortedBag(null); - fail("Expecting NullPointerException for null bag."); - } catch (final NullPointerException ex) { - // expected - } + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("collection")); assertSame("UnmodifiableSortedBag shall not be decorated", bag, BagUtils.unmodifiableSortedBag(bag)); } @@ -139,39 +129,35 @@ public void testUnmodifiableSortedBag() { @Test public void testPredicatedSortedBag() { final Bag bag = BagUtils.predicatedSortedBag(new TreeBag<>(), truePredicate); - assertTrue("Returned object should be a PredicatedSortedBag.", - bag instanceof PredicatedSortedBag); - try { + assertTrue(bag instanceof PredicatedSortedBag); + Exception exception = assertThrows(NullPointerException.class, () -> { BagUtils.predicatedSortedBag(null, truePredicate); - fail("Expecting NullPointerException for null bag."); - } catch (final NullPointerException ex) { - // expected - } - try { + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("collection")); + + exception = assertThrows(NullPointerException.class, () -> { BagUtils.predicatedSortedBag(new TreeBag<>(), null); - fail("Expecting NullPointerException for null predicate."); - } catch (final NullPointerException ex) { - // expected - } + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("predicate")); } @Test public void testTransformedSortedBag() { final Bag bag = BagUtils.transformingSortedBag(new TreeBag<>(), nopTransformer); - assertTrue("Returned object should be an TransformedSortedBag", - bag instanceof TransformedSortedBag); - try { + assertTrue(bag instanceof TransformedSortedBag); + Exception exception = assertThrows(NullPointerException.class, () -> { BagUtils.transformingSortedBag(null, nopTransformer); - fail("Expecting NullPointerException for null bag."); - } catch (final NullPointerException ex) { - // expected - } - try { + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("collection")); + + exception = assertThrows(NullPointerException.class, () -> { BagUtils.transformingSortedBag(new TreeBag<>(), null); - fail("Expecting NullPointerException for null transformer."); - } catch (final NullPointerException ex) { - // expected - } + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("transformer")); } } diff --git a/src/test/java/org/apache/commons/collections4/ClosureUtilsTest.java b/src/test/java/org/apache/commons/collections4/ClosureUtilsTest.java index 226713b6d5..dc2c637493 100644 --- a/src/test/java/org/apache/commons/collections4/ClosureUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/ClosureUtilsTest.java @@ -16,7 +16,11 @@ */ package org.apache.commons.collections4; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Collection; @@ -73,13 +77,12 @@ public void testExceptionClosure() { try { ClosureUtils.exceptionClosure().execute(null); } catch (final FunctorException ex) { - try { + Exception exception = assertThrows(FunctorException.class, () -> { ClosureUtils.exceptionClosure().execute(cString); - } catch (final FunctorException ex2) { - return; - } + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("ExceptionClosure invoked")); } - fail(); } // nopClosure @@ -135,18 +138,23 @@ public void testWhileClosure() { ClosureUtils.whileClosure(PredicateUtils.uniquePredicate(), cmd).execute(null); assertEquals(1, cmd.count); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.whileClosure(null, ClosureUtils.nopClosure()); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("predicate")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.whileClosure(FalsePredicate.falsePredicate(), null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("closure")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.whileClosure(null, null); - fail(); - } catch (final NullPointerException ex) {} + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("predicate")); } // doWhileClosure @@ -162,10 +170,11 @@ public void testDoWhileClosure() { ClosureUtils.doWhileClosure(cmd, PredicateUtils.uniquePredicate()).execute(null); assertEquals(2, cmd.count); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.doWhileClosure(null, null); - fail(); - } catch (final NullPointerException ex) {} + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("predicate")); } // chainedClosure @@ -199,29 +208,38 @@ public void testChainedClosure() { assertSame(NOPClosure.INSTANCE, ClosureUtils.chainedClosure()); assertSame(NOPClosure.INSTANCE, ClosureUtils.chainedClosure(Collections.>emptyList())); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.chainedClosure(null, null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("closures[0]")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.chainedClosure((Closure[]) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("closures")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.chainedClosure((Collection>) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("closures")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.chainedClosure(null, null); - fail(); - } catch (final NullPointerException ex) {} - try { - coll = new ArrayList<>(); - coll.add(null); - coll.add(null); - ClosureUtils.chainedClosure(coll); - fail(); - } catch (final NullPointerException ex) {} + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("closures")); + + final Collection> collection = new ArrayList<>(); + collection.add(null); + collection.add(null); + exception = assertThrows(NullPointerException.class, () -> { + ClosureUtils.chainedClosure(collection); + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("closures")); } // ifClosure @@ -319,28 +337,36 @@ public void testSwitchClosure() { map.put(null, null); assertEquals(NOPClosure.INSTANCE, ClosureUtils.switchClosure(map)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.switchClosure(null, null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("predicates")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.switchClosure((Predicate[]) null, (Closure[]) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("predicates")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.switchClosure((Map, Closure>) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("predicatesAndClosures")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.switchClosure(new Predicate[2], new Closure[2]); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("predicates[0]")); + + exception = assertThrows(IllegalArgumentException.class, () -> { ClosureUtils.switchClosure( new Predicate[] { TruePredicate.truePredicate() }, new Closure[] { a, b }); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + assertTrue(actualMessage.contains("predicates")); } // switchMapClosure @@ -380,10 +406,11 @@ public void testSwitchMapClosure() { assertEquals(NOPClosure.INSTANCE, ClosureUtils.switchMapClosure(new HashMap>())); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.switchMapClosure(null); - fail(); - } catch (final NullPointerException ex) {} + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("objectsAndClosures")); } // asClosure diff --git a/src/test/java/org/apache/commons/collections4/CollectionUtilsTest.java b/src/test/java/org/apache/commons/collections4/CollectionUtilsTest.java index 7d1bd98f2f..2eef755cf7 100644 --- a/src/test/java/org/apache/commons/collections4/CollectionUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/CollectionUtilsTest.java @@ -19,10 +19,10 @@ import static org.apache.commons.collections4.functors.EqualPredicate.equalPredicate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; @@ -305,22 +305,22 @@ public void containsAll() { multiples.add("1"); assertFalse("containsAll({1},{1,3}) should return false.", CollectionUtils.containsAll(one, odds)); - assertTrue("containsAll({1,3},{1}) should return true.", CollectionUtils.containsAll(odds, one)); + assertTrue(CollectionUtils.containsAll(odds, one)); assertFalse("containsAll({3},{1,3}) should return false.", CollectionUtils.containsAll(three, odds)); - assertTrue("containsAll({1,3},{3}) should return true.", CollectionUtils.containsAll(odds, three)); - assertTrue("containsAll({2},{2}) should return true.", CollectionUtils.containsAll(two, two)); - assertTrue("containsAll({1,3},{1,3}) should return true.", CollectionUtils.containsAll(odds, odds)); + assertTrue(CollectionUtils.containsAll(odds, three)); + assertTrue(CollectionUtils.containsAll(two, two)); + assertTrue(CollectionUtils.containsAll(odds, odds)); assertFalse("containsAll({2},{1,3}) should return false.", CollectionUtils.containsAll(two, odds)); assertFalse("containsAll({1,3},{2}) should return false.", CollectionUtils.containsAll(odds, two)); assertFalse("containsAll({1},{3}) should return false.", CollectionUtils.containsAll(one, three)); assertFalse("containsAll({3},{1}) should return false.", CollectionUtils.containsAll(three, one)); - assertTrue("containsAll({1,3},{}) should return true.", CollectionUtils.containsAll(odds, empty)); + assertTrue(CollectionUtils.containsAll(odds, empty)); assertFalse("containsAll({},{1,3}) should return false.", CollectionUtils.containsAll(empty, odds)); - assertTrue("containsAll({},{}) should return true.", CollectionUtils.containsAll(empty, empty)); + assertTrue(CollectionUtils.containsAll(empty, empty)); - assertTrue("containsAll({1,3},{1,3,1}) should return true.", CollectionUtils.containsAll(odds, multiples)); - assertTrue("containsAll({1,3,1},{1,3,1}) should return true.", CollectionUtils.containsAll(odds, odds)); + assertTrue(CollectionUtils.containsAll(odds, multiples)); + assertTrue(CollectionUtils.containsAll(odds, odds)); } @Test @@ -336,12 +336,12 @@ public void containsAnyInCollection() { odds.add("1"); odds.add("3"); - assertTrue("containsAny({1},{1,3}) should return true.", CollectionUtils.containsAny(one, odds)); - assertTrue("containsAny({1,3},{1}) should return true.", CollectionUtils.containsAny(odds, one)); - assertTrue("containsAny({3},{1,3}) should return true.", CollectionUtils.containsAny(three, odds)); - assertTrue("containsAny({1,3},{3}) should return true.", CollectionUtils.containsAny(odds, three)); - assertTrue("containsAny({2},{2}) should return true.", CollectionUtils.containsAny(two, two)); - assertTrue("containsAny({1,3},{1,3}) should return true.", CollectionUtils.containsAny(odds, odds)); + assertTrue(CollectionUtils.containsAny(one, odds)); + assertTrue(CollectionUtils.containsAny(odds, one)); + assertTrue(CollectionUtils.containsAny(three, odds)); + assertTrue(CollectionUtils.containsAny(odds, three)); + assertTrue(CollectionUtils.containsAny(two, two)); + assertTrue(CollectionUtils.containsAny(odds, odds)); assertFalse("containsAny({2},{1,3}) should return false.", CollectionUtils.containsAny(two, odds)); assertFalse("containsAny({1,3},{2}) should return false.", CollectionUtils.containsAny(odds, two)); @@ -393,12 +393,12 @@ public void containsAnyInArray() { odds.add("3"); final String[] oddsArr = {"1", "3"}; - assertTrue("containsAny({1},{1,3}) should return true.", CollectionUtils.containsAny(one, oddsArr)); - assertTrue("containsAny({1,3},{1}) should return true.", CollectionUtils.containsAny(odds, oneArr)); - assertTrue("containsAny({3},{1,3}) should return true.", CollectionUtils.containsAny(three, oddsArr)); - assertTrue("containsAny({1,3},{3}) should return true.", CollectionUtils.containsAny(odds, threeArr)); - assertTrue("containsAny({2},{2}) should return true.", CollectionUtils.containsAny(two, twoArr)); - assertTrue("containsAny({1,3},{1,3}) should return true.", CollectionUtils.containsAny(odds, oddsArr)); + assertTrue(CollectionUtils.containsAny(one, oddsArr)); + assertTrue(CollectionUtils.containsAny(odds, oneArr)); + assertTrue(CollectionUtils.containsAny(three, oddsArr)); + assertTrue(CollectionUtils.containsAny(odds, threeArr)); + assertTrue(CollectionUtils.containsAny(two, twoArr)); + assertTrue(CollectionUtils.containsAny(odds, oddsArr)); assertFalse("containsAny({2},{1,3}) should return false.", CollectionUtils.containsAny(two, oddsArr)); assertFalse("containsAny({1,3},{2}) should return false.", CollectionUtils.containsAny(odds, twoArr)); @@ -949,18 +949,15 @@ public void getFromMap() { assertEquals(expected, found); // Map index out of range - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { CollectionUtils.get(expected, 2); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException e) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("Entry does not exist: 0")); + + exception = assertThrows(IndexOutOfBoundsException.class, () -> { CollectionUtils.get(expected, -2); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Index cannot be negative: -2")); // Sorted map, entries exist, should respect order final SortedMap map = new TreeMap<>(); @@ -1002,13 +999,13 @@ public void getFromIterator() throws Exception { assertEquals(2, (int) CollectionUtils.get(iterator, 1)); // Iterator, non-existent entry - try { - CollectionUtils.get(iterator, 10); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException e) { - // expected - } - assertFalse(iterator.hasNext()); + final Iterator iteratorInteger = iterableA.iterator(); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(iteratorInteger, 10); + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("Entry does not exist: 0")); + assertFalse(iteratorInteger.hasNext()); } @Test @@ -1024,13 +1021,12 @@ public void getFromEnumeration() throws Exception { assertEquals("one", CollectionUtils.get(en, 1)); // Enumerator, non-existent entry - try { - CollectionUtils.get(en, 3); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException e) { - // expected - } - assertFalse(en.hasMoreElements()); + Enumeration enumerator = vector.elements(); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(enumerator, 3); + }); + assertTrue(exception.getMessage().contains("Entry does not exist:")); + assertFalse(enumerator.hasMoreElements()); } @Test(expected = IndexOutOfBoundsException.class) @@ -1226,11 +1222,10 @@ public void testSizeIsEmpty_Iterator() { @Test public void testSizeIsEmpty_Other() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { CollectionUtils.sizeIsEmpty("not a list"); - fail("Expecting IllegalArgumentException"); - } catch (final IllegalArgumentException ex) { - } + }); + assertTrue(exception.getMessage().contains("Unsupported object type: java.lang.String")); } // ----------------------------------------------------------------------- @@ -1511,7 +1506,7 @@ public void testAddIgnoreNullNullColl() { public void predicatedCollection() { final Predicate predicate = PredicateUtils.instanceofPredicate(Integer.class); final Collection collection = CollectionUtils.predicatedCollection(new ArrayList(), predicate); - assertTrue("returned object should be a PredicatedCollection", collection instanceof PredicatedCollection); + assertTrue(collection instanceof PredicatedCollection); } @Test(expected = NullPointerException.class) @@ -1807,7 +1802,7 @@ public void testRemoveAllNullSubColl() { public void testTransformedCollection() { final Transformer transformer = TransformerUtils.nopTransformer(); final Collection collection = CollectionUtils.transformingCollection(new ArrayList<>(), transformer); - assertTrue("returned object should be a TransformedCollection", collection instanceof TransformedCollection); + assertTrue(collection instanceof TransformedCollection); } @Test(expected = NullPointerException.class) @@ -1838,26 +1833,22 @@ public void testTransformedCollection_2() { @Deprecated public void testSynchronizedCollection() { final Collection col = CollectionUtils.synchronizedCollection(new ArrayList<>()); - assertTrue("Returned object should be a SynchronizedCollection.", col instanceof SynchronizedCollection); - try { + assertTrue(col instanceof SynchronizedCollection); + Exception exception = assertThrows(NullPointerException.class, () -> { CollectionUtils.synchronizedCollection(null); - fail("Expecting NullPointerException for null collection."); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("collection")); } @Test @Deprecated public void testUnmodifiableCollection() { final Collection col = CollectionUtils.unmodifiableCollection(new ArrayList<>()); - assertTrue("Returned object should be a UnmodifiableCollection.", col instanceof UnmodifiableCollection); - try { + assertTrue(col instanceof UnmodifiableCollection); + Exception exception = assertThrows(NullPointerException.class, () -> { CollectionUtils.unmodifiableCollection(null); - fail("Expecting NullPointerException for null collection."); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("collection")); } @Test @@ -2023,26 +2014,25 @@ public void testReverseArrayNull() { @Test public void extractSingleton() { - ArrayList coll = null; - try { + final ArrayList coll = null; + Exception exception = assertThrows(NullPointerException.class, () -> { CollectionUtils.extractSingleton(coll); - fail("expected NullPointerException from extractSingleton(null)"); - } catch (final NullPointerException e) { - } - coll = new ArrayList<>(); - try { - CollectionUtils.extractSingleton(coll); - fail("expected IllegalArgumentException from extractSingleton(empty)"); - } catch (final IllegalArgumentException e) { - } - coll.add("foo"); - assertEquals("foo", CollectionUtils.extractSingleton(coll)); - coll.add("bar"); - try { - CollectionUtils.extractSingleton(coll); - fail("expected IllegalArgumentException from extractSingleton(size == 2)"); - } catch (final IllegalArgumentException e) { - } + }); + assertTrue(exception.getMessage().contains("collection")); + + final ArrayList coll2 = new ArrayList<>(); + exception = assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.extractSingleton(coll2); + }); + assertTrue(exception.getMessage().contains("Can extract singleton only when collection size == 1")); + + coll2.add("foo"); + assertEquals("foo", CollectionUtils.extractSingleton(coll2)); + coll2.add("bar"); + exception = assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.extractSingleton(coll2); + }); + assertTrue(exception.getMessage().contains("Can extract singleton only when collection size == 1")); } /** @@ -2192,17 +2182,15 @@ public int hash(final String o) { assertTrue(remove.contains("CX")); assertTrue(remove.contains("XZ")); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { CollectionUtils.removeAll(null, null, DefaultEquator.defaultEquator()); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - } // this is what we want + }); + assertTrue(exception.getMessage().contains("collection")); - try { + exception = assertThrows(NullPointerException.class, () -> { CollectionUtils.removeAll(base, remove, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - } // this is what we want + }); + assertTrue(exception.getMessage().contains("equator")); } @Test @@ -2245,17 +2233,15 @@ public int hash(final String o) { assertTrue(retain.contains("CX")); assertTrue(retain.contains("XZ")); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { CollectionUtils.retainAll(null, null, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - } // this is what we want + }); + assertTrue(exception.getMessage().contains("collection")); - try { + exception = assertThrows(NullPointerException.class, () -> { CollectionUtils.retainAll(base, retain, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - } // this is what we want + }); + assertTrue(exception.getMessage().contains("equator")); } } diff --git a/src/test/java/org/apache/commons/collections4/ComparatorUtilsTest.java b/src/test/java/org/apache/commons/collections4/ComparatorUtilsTest.java index ae9af09be9..7993c4aa26 100644 --- a/src/test/java/org/apache/commons/collections4/ComparatorUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/ComparatorUtilsTest.java @@ -17,8 +17,9 @@ package org.apache.commons.collections4; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Comparator; @@ -63,19 +64,15 @@ public void max() { assertEquals(Integer.valueOf(1), ComparatorUtils.max(1, 10, reversed)); assertEquals(Integer.valueOf(-10), ComparatorUtils.max(10, -10, reversed)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ComparatorUtils.max(1, null, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(NullPointerException.class, () -> { ComparatorUtils.max(null, 10, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertNull(exception.getMessage()); } @Test @@ -89,19 +86,15 @@ public void min() { assertEquals(Integer.valueOf(10), ComparatorUtils.min(1, 10, reversed)); assertEquals(Integer.valueOf(10), ComparatorUtils.min(10, -10, reversed)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ComparatorUtils.min(1, null, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(NullPointerException.class, () -> { ComparatorUtils.min(null, 10, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertNull(exception.getMessage()); } @Test diff --git a/src/test/java/org/apache/commons/collections4/EnumerationUtilsTest.java b/src/test/java/org/apache/commons/collections4/EnumerationUtilsTest.java index 0c37ca5f5b..f2af06f9e5 100644 --- a/src/test/java/org/apache/commons/collections4/EnumerationUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/EnumerationUtilsTest.java @@ -17,9 +17,10 @@ package org.apache.commons.collections4; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Enumeration; @@ -50,13 +51,13 @@ public void getFromEnumeration() throws Exception { en = vector.elements(); assertEquals("one", EnumerationUtils.get(en, 1)); + final Enumeration enumeration = vector.elements(); // Enumerator, non-existent entry - try { - EnumerationUtils.get(en, 3); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException e) { - // expected - } + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + EnumerationUtils.get(enumeration, 3); + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("Entry does not exist: 1")); assertTrue(!en.hasMoreElements()); } @@ -76,12 +77,10 @@ public void testAsIterableFor() { @Test public void testAsIterableForNull() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { EnumerationUtils.asIterable((Enumeration) null).iterator().next(); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // success - } + }); + assertNull(exception.getMessage()); } @Test diff --git a/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java b/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java index b003a94cff..bc2be12a91 100644 --- a/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java @@ -19,10 +19,10 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.IOException; import java.io.Serializable; @@ -50,13 +50,11 @@ public void testExceptionFactory() { try { FactoryUtils.exceptionFactory().create(); } catch (final FunctorException ex) { - try { + Exception exception = assertThrows(FunctorException.class, () -> { FactoryUtils.exceptionFactory().create(); - } catch (final FunctorException ex2) { - return; - } + }); + assertTrue(exception.getMessage().contains("ExceptionFactory invoked")); } - fail(); } // nullFactory @@ -139,18 +137,15 @@ public void testPrototypeFactoryPublicSerializationError() { assertTrue(ex.getCause() instanceof IOException); return; } - fail(); } @Test public void testPrototypeFactoryPublicBad() { final Object proto = new Object(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { FactoryUtils.prototypeFactory(proto); - } catch (final IllegalArgumentException ex) { - return; - } - fail(); + }); + assertTrue(exception.getMessage().contains("The prototype must be cloneable via a public clone method")); } public static class Mock1 { diff --git a/src/test/java/org/apache/commons/collections4/FluentIterableTest.java b/src/test/java/org/apache/commons/collections4/FluentIterableTest.java index 4b7277713f..1456244d67 100644 --- a/src/test/java/org/apache/commons/collections4/FluentIterableTest.java +++ b/src/test/java/org/apache/commons/collections4/FluentIterableTest.java @@ -21,8 +21,9 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; @@ -121,12 +122,10 @@ public void factoryMethodOf() { assertTrue(result.isEmpty()); final Iterable it = null; - try { + Exception exception = assertThrows(NullPointerException.class, () -> { FluentIterable.of(it).toList(); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("iterable")); } @Test @@ -164,12 +163,10 @@ public void collate() { Collections.sort(combinedList); assertEquals(combinedList, result); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { FluentIterable.of(iterableOdd).collate(null).toList(); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("iterable")); } @Test @@ -202,12 +199,10 @@ public void filter() { result = FluentIterable.of(emptyIterable).filter(smallerThan3).toList(); assertEquals(0, result.size()); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { FluentIterable.of(iterableA).filter(null).toList(); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test @@ -222,12 +217,10 @@ public void forEach() { } assertEquals(expectedSum, sum.get()); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { FluentIterable.of(iterableA).forEach((Closure) null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("closure")); } @Test @@ -250,12 +243,10 @@ public void limit() { result = FluentIterable.of(emptyIterable).limit(3).toList(); assertEquals(0, result.size()); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { FluentIterable.of(iterableA).limit(-2).toList(); - fail("expecting IllegalArgumentException"); - } catch (final IllegalArgumentException iae) { - // expected - } + }); + assertTrue(exception.getMessage().contains("MaxSize parameter must not be negative.")); } @Test @@ -290,12 +281,10 @@ public void skip() { result = FluentIterable.of(emptyIterable).skip(3).toList(); assertEquals(0, result.size()); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { FluentIterable.of(iterableA).skip(-4).toList(); - fail("expecting IllegalArgumentException"); - } catch (final IllegalArgumentException iae) { - // expected - } + }); + assertTrue(exception.getMessage().contains("ElementsToSkip parameter must not be negative")); } @Test @@ -309,12 +298,10 @@ public void transform() { result = FluentIterable.of(emptyIterable).transform(squared).toList(); assertEquals(0, result.size()); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { FluentIterable.of(iterableA).transform(null).toList(); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("transformer")); } @Test @@ -333,12 +320,10 @@ public void unmodifiable() { final FluentIterable iterable1 = FluentIterable.of(iterableA).unmodifiable(); final Iterator it = iterable1.iterator(); assertEquals(1, it.next().intValue()); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { it.remove(); - fail("expecting UnsupportedOperationException"); - } catch (final UnsupportedOperationException ise) { - // expected - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); // calling unmodifiable on an already unmodifiable iterable shall return the same instance final FluentIterable iterable2 = iterable1.unmodifiable(); @@ -355,12 +340,10 @@ public void zip() { Collections.sort(combinedList); assertEquals(combinedList, result); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { FluentIterable.of(iterableOdd).zip((Iterable) null).toList(); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("iterable")); result = FluentIterable .of(Arrays.asList(1, 4, 7)) @@ -386,12 +369,10 @@ public void allMatch() { assertFalse(FluentIterable.of(iterableOdd).allMatch(EVEN)); assertFalse(FluentIterable.of(iterableA).allMatch(EVEN)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { FluentIterable.of(iterableEven).allMatch(null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test @@ -400,12 +381,10 @@ public void anyMatch() { assertFalse(FluentIterable.of(iterableOdd).anyMatch(EVEN)); assertTrue(FluentIterable.of(iterableA).anyMatch(EVEN)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { FluentIterable.of(iterableEven).anyMatch(null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test @@ -464,12 +443,10 @@ public void copyInto() { assertEquals(expected.size(), result.size()); assertEquals(expected, result); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { FluentIterable.of(iterableA).copyInto(null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("collection")); } @Test @@ -485,18 +462,18 @@ public void iterator() { public void get() { assertEquals(2, FluentIterable.of(iterableEven).get(0).intValue()); - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { FluentIterable.of(iterableEven).get(-1); - fail("expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ioe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Index cannot be negative: -1")); - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { FluentIterable.of(iterableEven).get(IterableUtils.size(iterableEven)); - fail("expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ioe) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("6")); } } diff --git a/src/test/java/org/apache/commons/collections4/IterableUtilsTest.java b/src/test/java/org/apache/commons/collections4/IterableUtilsTest.java index b26d9c117d..4bd0ea344d 100644 --- a/src/test/java/org/apache/commons/collections4/IterableUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/IterableUtilsTest.java @@ -19,10 +19,11 @@ import static org.apache.commons.collections4.functors.EqualPredicate.equalPredicate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; @@ -110,12 +111,11 @@ public void forEach() { col.add(listB); IterableUtils.forEach(col, testClosure); assertTrue(listA.isEmpty() && listB.isEmpty()); - try { + + Exception exception = assertThrows(NullPointerException.class, () -> { IterableUtils.forEach(col, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("closure")); IterableUtils.forEach(null, testClosure); @@ -148,12 +148,11 @@ public void forEachButLast() { assertTrue(listA.isEmpty() && !listB.isEmpty()); assertSame(listB, last); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IterableUtils.forEachButLast(col, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("closure")); + IterableUtils.forEachButLast(null, testClosure); @@ -191,11 +190,11 @@ public int hash(final String o) { assertFalse(IterableUtils.contains(base, "CX", secondLetterEquator)); assertFalse(IterableUtils.contains(null, null, secondLetterEquator)); - try { + // this is what we want + Exception exception = assertThrows(NullPointerException.class, () -> { IterableUtils.contains(base, "AC", null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - } // this is what we want + }); + assertTrue(exception.getMessage().contains("equator")); } @Test @@ -273,12 +272,10 @@ public void find() { test = IterableUtils.find(iterableA, testPredicate); assertNull(test); assertNull(IterableUtils.find(null, testPredicate)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IterableUtils.find(iterableA, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test @@ -290,12 +287,10 @@ public void indexOf() { index = IterableUtils.indexOf(iterableA, testPredicate); assertEquals(-1, index); assertEquals(-1, IterableUtils.indexOf(null, testPredicate)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IterableUtils.indexOf(iterableA, null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test @@ -303,38 +298,30 @@ public void countMatches() { assertEquals(4, IterableUtils.countMatches(iterableB, EQUALS_TWO)); assertEquals(0, IterableUtils.countMatches(null, EQUALS_TWO)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { assertEquals(0, IterableUtils.countMatches(iterableA, null)); - fail("predicate must not be null"); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); - try { + exception = assertThrows(NullPointerException.class, () -> { assertEquals(0, IterableUtils.countMatches(null, null)); - fail("predicate must not be null"); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test public void matchesAny() { final List list = new ArrayList<>(); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { assertFalse(IterableUtils.matchesAny(null, null)); - fail("predicate must not be null"); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); - try { + exception = assertThrows(NullPointerException.class, () -> { assertFalse(IterableUtils.matchesAny(list, null)); - fail("predicate must not be null"); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); assertFalse(IterableUtils.matchesAny(null, EQUALS_TWO)); assertFalse(IterableUtils.matchesAny(list, EQUALS_TWO)); @@ -349,19 +336,15 @@ public void matchesAny() { @Test public void matchesAll() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { assertFalse(IterableUtils.matchesAll(null, null)); - fail("predicate must not be null"); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); - try { + exception = assertThrows(NullPointerException.class, () -> { assertFalse(IterableUtils.matchesAll(iterableA, null)); - fail("predicate must not be null"); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); final Predicate lessThanFive = object -> object < 5; assertTrue(IterableUtils.matchesAll(iterableA, lessThanFive)); @@ -434,12 +417,10 @@ public void partition() { assertEquals(1, partitions.size()); assertEquals(input, partitions.get(0)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IterableUtils.partition(input, (Predicate) null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @SuppressWarnings("unchecked") @@ -542,42 +523,34 @@ public void testToStringWithNullArguments() { }, "", "(", ")"); assertEquals("()", result); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IterableUtils.toString(new ArrayList(), null, "", "(", ")"); - fail("expecting NullPointerException"); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("transformer")); - try { + exception = assertThrows(NullPointerException.class, () -> { IterableUtils.toString(new ArrayList(), input -> { fail("not supposed to reach here"); return ""; }, null, "(", ")"); - fail("expecting NullPointerException"); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("delimiter")); - try { + exception = assertThrows(NullPointerException.class, () -> { IterableUtils.toString(new ArrayList(), input -> { fail("not supposed to reach here"); return ""; }, "", null, ")"); - fail("expecting NullPointerException"); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("prefix")); - try { + exception = assertThrows(NullPointerException.class, () -> { IterableUtils.toString(new ArrayList(), input -> { fail("not supposed to reach here"); return ""; }, "", "(", null); - fail("expecting NullPointerException"); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("suffix")); } @Test diff --git a/src/test/java/org/apache/commons/collections4/IteratorUtilsTest.java b/src/test/java/org/apache/commons/collections4/IteratorUtilsTest.java index 4065df004c..34640f97b4 100644 --- a/src/test/java/org/apache/commons/collections4/IteratorUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/IteratorUtilsTest.java @@ -23,10 +23,10 @@ import static org.easymock.EasyMock.replay; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; @@ -162,64 +162,50 @@ public void testArrayIterator() { iterator.reset(); assertEquals("a", iterator.next()); - try { - iterator = IteratorUtils.arrayIterator(Integer.valueOf(0)); - fail("Expecting IllegalArgumentException"); - } catch (final IllegalArgumentException ex) { - // expected - } + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + IteratorUtils.arrayIterator(Integer.valueOf(0)); + }); + assertTrue(exception.getMessage().contains("Argument is not an array")); - try { - iterator = IteratorUtils.arrayIterator((Object[]) null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // expected - } + exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.arrayIterator((Object[]) null); + }); + assertNull(exception.getMessage()); iterator = IteratorUtils.arrayIterator(objArray, 1); assertEquals("b", iterator.next()); - try { - iterator = IteratorUtils.arrayIterator(objArray, -1); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayIterator(objArray, -1); + }); + assertTrue(exception.getMessage().contains("Start index must not be less than zero")); iterator = IteratorUtils.arrayIterator(objArray, 3); assertFalse(iterator.hasNext()); iterator.reset(); - try { - iterator = IteratorUtils.arrayIterator(objArray, 4); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayIterator(objArray, 4); + }); + assertTrue(exception.getMessage().contains("Start index must not be greater than the array length")); iterator = IteratorUtils.arrayIterator(objArray, 2, 3); assertEquals("c", iterator.next()); - try { - iterator = IteratorUtils.arrayIterator(objArray, 2, 4); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayIterator(objArray, 2, 4); + }); + assertTrue(exception.getMessage().contains("End index must not be greater than the array length")); - try { - iterator = IteratorUtils.arrayIterator(objArray, -1, 1); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayIterator(objArray, -1, 1); + }); + assertTrue(exception.getMessage().contains("Start index must not be less than zero")); - try { - iterator = IteratorUtils.arrayIterator(objArray, 2, 1); - fail("Expecting IllegalArgumentException"); - } catch (final IllegalArgumentException ex) { - // expected - } + exception = assertThrows(IllegalArgumentException.class, () -> { + IteratorUtils.arrayIterator(objArray, 2, 1); + }); + assertTrue(exception.getMessage().contains("End index must not be less than start index")); final int[] intArray = { 0, 1, 2 }; iterator = IteratorUtils.arrayIterator(intArray); @@ -231,47 +217,37 @@ public void testArrayIterator() { iterator = IteratorUtils.arrayIterator(intArray, 1); assertEquals(1, iterator.next()); - try { - iterator = IteratorUtils.arrayIterator(intArray, -1); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayIterator(intArray, -1); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that starts before the start of the array.")); iterator = IteratorUtils.arrayIterator(intArray, 3); assertFalse(iterator.hasNext()); iterator.reset(); - try { - iterator = IteratorUtils.arrayIterator(intArray, 4); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayIterator(intArray, 4); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that starts beyond the end of the array.")); iterator = IteratorUtils.arrayIterator(intArray, 2, 3); assertEquals(2, iterator.next()); - try { - iterator = IteratorUtils.arrayIterator(intArray, 2, 4); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayIterator(intArray, 2, 4); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that ends beyond the end of the array.")); - try { - iterator = IteratorUtils.arrayIterator(intArray, -1, 1); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayIterator(intArray, -1, 1); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that starts before the start of the array.")); - try { - iterator = IteratorUtils.arrayIterator(intArray, 2, 1); - fail("Expecting IllegalArgumentException"); - } catch (final IllegalArgumentException ex) { - // expected - } + exception = assertThrows(IllegalArgumentException.class, () -> { + IteratorUtils.arrayIterator(intArray, 2, 1); + }); + assertTrue(exception.getMessage().contains("End index must not be less than start index.")); } @Test @@ -292,19 +268,15 @@ public void testArrayListIterator() { assertEquals(4, iterator.nextIndex()); // size of list assertEquals(3, iterator.previousIndex()); - try { - iterator = IteratorUtils.arrayListIterator(Integer.valueOf(0)); - fail("Expecting IllegalArgumentException"); - } catch (final IllegalArgumentException ex) { - // expected - } + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + IteratorUtils.arrayListIterator(Integer.valueOf(0)); + }); + assertTrue(exception.getMessage().contains("Argument is not an array")); - try { - iterator = IteratorUtils.arrayListIterator((Object[]) null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // expected - } + exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.arrayListIterator((Object[]) null); + }); + assertNull(exception.getMessage()); iterator = IteratorUtils.arrayListIterator(objArray, 1); assertEquals(-1, iterator.previousIndex()); @@ -313,52 +285,40 @@ public void testArrayListIterator() { assertEquals("b", iterator.next()); assertEquals(0, iterator.previousIndex()); - try { - iterator = IteratorUtils.arrayListIterator(objArray, -1); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayListIterator(objArray, -1); + }); + assertTrue(exception.getMessage().contains("Start index must not be less than zero")); - iterator = IteratorUtils.arrayListIterator(objArray, 3); - assertTrue(iterator.hasNext()); - try { - iterator.previous(); - fail("Expecting NoSuchElementException."); - } catch (final NoSuchElementException ex) { - // expected - } + final ResettableListIterator listIterator = IteratorUtils.arrayListIterator(objArray, 3); + assertTrue(listIterator.hasNext()); + exception = assertThrows(NoSuchElementException.class, () -> { + listIterator.previous(); + }); + assertNull(exception.getMessage()); - try { - iterator = IteratorUtils.arrayListIterator(objArray, 5); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayListIterator(objArray, 5); + }); + assertTrue(exception.getMessage().contains("Start index must not be greater than the array length")); iterator = IteratorUtils.arrayListIterator(objArray, 2, 3); assertEquals("c", iterator.next()); - try { - iterator = IteratorUtils.arrayListIterator(objArray, 2, 5); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayListIterator(objArray, 2, 5); + }); + assertTrue(exception.getMessage().contains("End index must not be greater than the array length")); - try { - iterator = IteratorUtils.arrayListIterator(objArray, -1, 1); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayListIterator(objArray, -1, 1); + }); + assertTrue(exception.getMessage().contains("Start index must not be less than zero")); - try { - iterator = IteratorUtils.arrayListIterator(objArray, 2, 1); - fail("Expecting IllegalArgumentException"); - } catch (final IllegalArgumentException ex) { - // expected - } + exception = assertThrows(IllegalArgumentException.class, () -> { + IteratorUtils.arrayListIterator(objArray, 2, 1); + }); + assertTrue(exception.getMessage().contains("End index must not be less than start index")); final int[] intArray = { 0, 1, 2 }; iterator = IteratorUtils.arrayListIterator(intArray); @@ -390,22 +350,17 @@ public void testArrayListIterator() { assertEquals(0, iterator.previousIndex()); assertEquals(1, iterator.nextIndex()); - try { - iterator = IteratorUtils.arrayListIterator(intArray, -1); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayListIterator(intArray, -1); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that starts before the start of the array.")); iterator = IteratorUtils.arrayListIterator(intArray, 3); - assertFalse(iterator.hasNext()); - try { - iterator = IteratorUtils.arrayListIterator(intArray, 4); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayListIterator(intArray, 4); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that starts beyond the end of the array.")); iterator = IteratorUtils.arrayListIterator(intArray, 2, 3); assertFalse(iterator.hasPrevious()); @@ -414,26 +369,20 @@ public void testArrayListIterator() { assertTrue(iterator.hasPrevious()); assertFalse(iterator.hasNext()); - try { - iterator = IteratorUtils.arrayListIterator(intArray, 2, 4); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayListIterator(intArray, 2, 4); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that ends beyond the end of the array.")); - try { - iterator = IteratorUtils.arrayListIterator(intArray, -1, 1); - fail("Expecting IndexOutOfBoundsException"); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.arrayListIterator(intArray, -1, 1); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that starts before the start of the array.")); - try { - iterator = IteratorUtils.arrayListIterator(intArray, 2, 1); - fail("Expecting IllegalArgumentException"); - } catch (final IllegalArgumentException ex) { - // expected - } + exception = assertThrows(IllegalArgumentException.class, () -> { + IteratorUtils.arrayListIterator(intArray, 2, 1); + }); + assertTrue(exception.getMessage().contains("End index must not be less than start index.")); } @Test(expected = NullPointerException.class) @@ -464,12 +413,10 @@ public void testAsIterable() { @Test public void testAsIterableNull() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.asIterable(null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("iterator")); } @Test(expected = NullPointerException.class) @@ -478,7 +425,7 @@ public void testAsIterator() { vector.addElement("zero"); vector.addElement("one"); final Enumeration en = vector.elements(); - assertTrue("create instance fail", IteratorUtils.asIterator(en) instanceof Iterator); + assertTrue(IteratorUtils.asIterator(en) instanceof Iterator); IteratorUtils.asIterator(null); } @@ -490,7 +437,7 @@ public void testAsIteratorNull() { vector.addElement("test"); vector.addElement("one"); final Enumeration en = vector.elements(); - assertTrue("create instance fail", IteratorUtils.asIterator(en, coll) instanceof Iterator); + assertTrue(IteratorUtils.asIterator(en, coll) instanceof Iterator); try { IteratorUtils.asIterator(null, coll); } catch (final NullPointerException npe) { @@ -532,21 +479,19 @@ public void testAsMultipleIterable() { @Test public void testAsMultipleIterableNull() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.asMultipleUseIterable(null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("iterator")); } @Test public void testChainedIterator() { final ArrayList arrayList = new ArrayList(); final Iterator ie = arrayList.iterator(); - assertTrue("create instance fail", IteratorUtils.chainedIterator(ie) instanceof Iterator); + assertTrue(IteratorUtils.chainedIterator(ie) instanceof Iterator); final Collection> coll = new ArrayList(); - assertTrue("create instance fail", IteratorUtils.chainedIterator(coll) instanceof Iterator); + assertTrue(IteratorUtils.chainedIterator(coll) instanceof Iterator); } @@ -555,19 +500,15 @@ public void testChainedIterator() { */ @Test public void testCollatedIterator() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.collatedIterator(null, collectionOdd.iterator(), null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("iterator")); - try { + exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.collatedIterator(null, null, collectionEven.iterator()); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("iterator")); // natural ordering Iterator it = IteratorUtils.collatedIterator(null, collectionOdd.iterator(), @@ -652,16 +593,15 @@ public void testEmptyIterator() { IteratorUtils.EMPTY_ITERATOR.reset(); assertSame(IteratorUtils.EMPTY_ITERATOR, IteratorUtils.EMPTY_ITERATOR); assertSame(IteratorUtils.EMPTY_ITERATOR, IteratorUtils.emptyIterator()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { IteratorUtils.EMPTY_ITERATOR.next(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.EMPTY_ITERATOR.remove(); - fail(); - } catch (final IllegalStateException ex) { - } + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); } // ----------------------------------------------------------------------- @@ -683,31 +623,26 @@ public void testEmptyListIterator() { IteratorUtils.EMPTY_LIST_ITERATOR.reset(); assertSame(IteratorUtils.EMPTY_LIST_ITERATOR, IteratorUtils.EMPTY_LIST_ITERATOR); assertSame(IteratorUtils.EMPTY_LIST_ITERATOR, IteratorUtils.emptyListIterator()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { IteratorUtils.EMPTY_LIST_ITERATOR.next(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(NoSuchElementException.class, () -> { IteratorUtils.EMPTY_LIST_ITERATOR.previous(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.EMPTY_LIST_ITERATOR.remove(); - fail(); - } catch (final IllegalStateException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.emptyListIterator().set(null); - fail(); - } catch (final IllegalStateException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(UnsupportedOperationException.class, () -> { IteratorUtils.emptyListIterator().add(null); - fail(); - } catch (final UnsupportedOperationException ex) { - } + }); + assertTrue(exception.getMessage().contains("add() not supported for empty Iterator")); } // ----------------------------------------------------------------------- @@ -728,31 +663,26 @@ public void testEmptyMapIterator() { ((ResettableIterator) IteratorUtils.EMPTY_MAP_ITERATOR).reset(); assertSame(IteratorUtils.EMPTY_MAP_ITERATOR, IteratorUtils.EMPTY_MAP_ITERATOR); assertSame(IteratorUtils.EMPTY_MAP_ITERATOR, IteratorUtils.emptyMapIterator()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { IteratorUtils.EMPTY_MAP_ITERATOR.next(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.EMPTY_MAP_ITERATOR.remove(); - fail(); - } catch (final IllegalStateException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.EMPTY_MAP_ITERATOR.getKey(); - fail(); - } catch (final IllegalStateException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.EMPTY_MAP_ITERATOR.getValue(); - fail(); - } catch (final IllegalStateException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.EMPTY_MAP_ITERATOR.setValue(null); - fail(); - } catch (final IllegalStateException ex) { - } + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); } // ----------------------------------------------------------------------- @@ -773,21 +703,18 @@ public void testEmptyOrderedIterator() { ((ResettableIterator) IteratorUtils.EMPTY_ORDERED_ITERATOR).reset(); assertSame(IteratorUtils.EMPTY_ORDERED_ITERATOR, IteratorUtils.EMPTY_ORDERED_ITERATOR); assertSame(IteratorUtils.EMPTY_ORDERED_ITERATOR, IteratorUtils.emptyOrderedIterator()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { IteratorUtils.EMPTY_ORDERED_ITERATOR.next(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(NoSuchElementException.class, () -> { IteratorUtils.EMPTY_ORDERED_ITERATOR.previous(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.EMPTY_ORDERED_ITERATOR.remove(); - fail(); - } catch (final IllegalStateException ex) { - } + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); } // ----------------------------------------------------------------------- @@ -808,36 +735,30 @@ public void testEmptyOrderedMapIterator() { ((ResettableIterator) IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR).reset(); assertSame(IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR, IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR); assertSame(IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR, IteratorUtils.emptyOrderedMapIterator()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.next(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(NoSuchElementException.class, () -> { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.previous(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.remove(); - fail(); - } catch (final IllegalStateException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(NoSuchElementException.class, () -> { + IteratorUtils.EMPTY_ORDERED_ITERATOR.previous(); + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.getKey(); - fail(); - } catch (final IllegalStateException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.getValue(); - fail(); - } catch (final IllegalStateException ex) { - } - try { - IteratorUtils.EMPTY_ORDERED_MAP_ITERATOR.setValue(null); - fail(); - } catch (final IllegalStateException ex) { - } + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); } @Test @@ -861,8 +782,7 @@ public void testFilteredListIterator() { final List arrayList = new ArrayList(); arrayList.add("test"); final Predicate predicate = INSTANCE; - assertTrue("create instance fail", - IteratorUtils.filteredListIterator(arrayList.listIterator(), predicate) instanceof ListIterator); + assertTrue(IteratorUtils.filteredListIterator(arrayList.listIterator(), predicate) instanceof ListIterator); try { IteratorUtils.filteredListIterator(null, predicate); } catch (final NullPointerException npe) { @@ -884,12 +804,10 @@ public void testFind() { test = IteratorUtils.find(iterableA.iterator(), testPredicate); assertNull(test); assertNull(IteratorUtils.find(null, testPredicate)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { assertNull(IteratorUtils.find(iterableA.iterator(), null)); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test @@ -914,12 +832,10 @@ public void testForEach() { col.add(listB); IteratorUtils.forEach(col.iterator(), testClosure); assertTrue(listA.isEmpty() && listB.isEmpty()); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.forEach(col.iterator(), null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("closure")); IteratorUtils.forEach(null, testClosure); @@ -944,12 +860,10 @@ public void testForEachButLast() { assertTrue(listA.isEmpty() && !listB.isEmpty()); assertSame(listB, last); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.forEachButLast(col.iterator(), null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("closure")); IteratorUtils.forEachButLast(null, testClosure); @@ -968,14 +882,13 @@ public void testGetAtIndexFromIterator() throws Exception { iterator = iterableA.iterator(); assertEquals(2, (int) IteratorUtils.get(iterator, 1)); + final Iterator iteratorInteger = iterableA.iterator(); // Iterator, non-existent entry - try { - IteratorUtils.get(iterator, 10); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException e) { - // expected - } - assertFalse(iterator.hasNext()); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IteratorUtils.get(iteratorInteger, 10); + }); + assertTrue(exception.getMessage().contains("Entry does not exist: 0")); + assertFalse(iteratorInteger.hasNext()); } @Test @@ -985,25 +898,19 @@ public void testGetIterator() { final Node[] nodes = createNodes(); final NodeList nodeList = createNodeList(nodes); - assertTrue("returns empty iterator when null passed", IteratorUtils.getIterator(null) instanceof EmptyIterator); - assertTrue("returns Iterator when Iterator directly ", - IteratorUtils.getIterator(iterableA.iterator()) instanceof Iterator); - assertTrue("returns Iterator when iterable passed", IteratorUtils.getIterator(iterableA) instanceof Iterator); - assertTrue("returns ObjectArrayIterator when Object array passed", - IteratorUtils.getIterator(objArray) instanceof ObjectArrayIterator); - assertTrue("returns Iterator when Map passed", IteratorUtils.getIterator(inMap) instanceof Iterator); - assertTrue("returns NodeListIterator when nodeList passed", - IteratorUtils.getIterator(nodeList) instanceof NodeListIterator); - assertTrue("returns EnumerationIterator when Enumeration passed", - IteratorUtils.getIterator(new Vector().elements()) instanceof EnumerationIterator); + assertTrue(IteratorUtils.getIterator(null) instanceof EmptyIterator); + assertTrue(IteratorUtils.getIterator(iterableA.iterator()) instanceof Iterator); + assertTrue(IteratorUtils.getIterator(iterableA) instanceof Iterator); + assertTrue(IteratorUtils.getIterator(objArray) instanceof ObjectArrayIterator); + assertTrue(IteratorUtils.getIterator(inMap) instanceof Iterator); + assertTrue(IteratorUtils.getIterator(nodeList) instanceof NodeListIterator); + assertTrue(IteratorUtils.getIterator(new Vector().elements()) instanceof EnumerationIterator); final Node node1 = createMock(Node.class); - assertTrue("returns NodeListIterator when nodeList passed", - IteratorUtils.getIterator(node1) instanceof NodeListIterator); + assertTrue(IteratorUtils.getIterator(node1) instanceof NodeListIterator); final Dictionary dic = createMock(Dictionary.class); - assertTrue("returns EnumerationIterator when Dictionary passed", - IteratorUtils.getIterator(dic) instanceof EnumerationIterator); + assertTrue(IteratorUtils.getIterator(dic) instanceof EnumerationIterator); final int[] arr = new int[8]; - assertTrue("returns ArrayIterator when array passed", IteratorUtils.getIterator(arr) instanceof ArrayIterator); + assertTrue(IteratorUtils.getIterator(arr) instanceof ArrayIterator); } @Test @@ -1015,12 +922,10 @@ public void testIndexOf() { index = IteratorUtils.indexOf(iterableA.iterator(), testPredicate); assertEquals(-1, index); assertEquals(-1, IteratorUtils.indexOf(null, testPredicate)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.indexOf(iterableA.iterator(), null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test(expected = NullPointerException.class) @@ -1030,7 +935,7 @@ public void testLoopingIterator() { final Collection coll = new ArrayList(); coll.add("test"); final Iterator ie = arrayList.iterator(); - assertTrue("create instance fail", IteratorUtils.loopingIterator(coll) instanceof ResettableIterator); + assertTrue(IteratorUtils.loopingIterator(coll) instanceof ResettableIterator); IteratorUtils.loopingIterator(null); } @@ -1039,7 +944,7 @@ public void testLoopingListIterator() { final ArrayList arrayList = new ArrayList(); arrayList.add("test"); final Iterator ie = arrayList.iterator(); - assertTrue("create instance fail", IteratorUtils.loopingListIterator(arrayList) instanceof ResettableIterator); + assertTrue(IteratorUtils.loopingListIterator(arrayList) instanceof ResettableIterator); IteratorUtils.loopingListIterator(null); } @@ -1067,12 +972,10 @@ public void testNodeIterator() { // single use iterator assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext()); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.nodeListIterator((Node) null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("node")); } /** @@ -1096,24 +999,22 @@ public void testNodeListIterator() { // single use iterator assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext()); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.nodeListIterator((NodeList) null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("nodeList")); } @Test public void testObjectGraphIterator() { - assertTrue("create instance fail", IteratorUtils.objectGraphIterator(null, null) instanceof Iterator); + assertTrue(IteratorUtils.objectGraphIterator(null, null) instanceof Iterator); } @Test(expected = NullPointerException.class) public void testPeekingIterator() { final ArrayList arrayList = new ArrayList(); final Iterator ie = arrayList.iterator(); - assertTrue("create instance fail", IteratorUtils.peekingIterator(ie) instanceof Iterator); + assertTrue(IteratorUtils.peekingIterator(ie) instanceof Iterator); IteratorUtils.peekingIterator(null); } @@ -1122,18 +1023,18 @@ public void testPeekingIterator() { public void testPushBackIterator() { final ArrayList arrayList = new ArrayList(); final Iterator ie = arrayList.iterator(); - assertTrue("create instance fail", IteratorUtils.pushbackIterator(ie) instanceof Iterator); + assertTrue(IteratorUtils.pushbackIterator(ie) instanceof Iterator); IteratorUtils.pushbackIterator(null); } @Test public void testSingletonIterator() { - assertTrue("create instance fail", IteratorUtils.singletonIterator(new Object()) instanceof ResettableIterator); + assertTrue(IteratorUtils.singletonIterator(new Object()) instanceof ResettableIterator); } @Test public void testSingletonListIterator() { - assertTrue("create instance fail", IteratorUtils.singletonListIterator(new Object()) instanceof Iterator); + assertTrue(IteratorUtils.singletonListIterator(new Object()) instanceof Iterator); } @Test @@ -1145,12 +1046,10 @@ public void testToArray() { final Object[] result = IteratorUtils.toArray(list.iterator()); assertEquals(list, Arrays.asList(result)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.toArray(null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("iterator")); } @Test @@ -1162,19 +1061,15 @@ public void testToArray2() { final String[] result = IteratorUtils.toArray(list.iterator(), String.class); assertEquals(list, Arrays.asList(result)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.toArray(list.iterator(), null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("arrayClass")); - try { + exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.toArray(null, String.class); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("iterator")); } @Test @@ -1186,20 +1081,15 @@ public void testToList() { final List result = IteratorUtils.toList(list.iterator()); assertEquals(list, result); // add - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.toList(null, 10); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("iterator")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { IteratorUtils.toList(list.iterator(), -1); - fail("Expecting IllegalArgumentException"); - } catch (final IllegalArgumentException ex) { - // success - } - + }); + assertTrue(exception.getMessage().contains("Estimated size must be greater than 0")); } @Test @@ -1220,12 +1110,10 @@ public void testToListIterator() { @Test public void testToListIteratorNull() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IteratorUtils.toListIterator(null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("iterator")); } @Test @@ -1251,23 +1139,17 @@ public void testTransformedIterator() { public void testUnmodifiableIteratorImmutability() { final Iterator iterator = getImmutableIterator(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { iterator.remove(); - // We shouldn't get to here. - fail("remove() should throw an UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // This is correct; ignore the exception. - } - + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); iterator.next(); - try { + // We shouldn't get to here. + exception = assertThrows(UnsupportedOperationException.class, () -> { iterator.remove(); - // We shouldn't get to here. - fail("remove() should throw an UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // This is correct; ignore the exception. - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); } @@ -1305,55 +1187,37 @@ public void testUnmodifiableIteratorIteration() { public void testUnmodifiableListIteratorImmutability() { final ListIterator listIterator = getImmutableListIterator(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { listIterator.remove(); - // We shouldn't get to here. - fail("remove() should throw an UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // This is correct; ignore the exception. - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { listIterator.set("a"); - // We shouldn't get to here. - fail("set(Object) should throw an UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // This is correct; ignore the exception. - } + }); + assertTrue(exception.getMessage().contains("set() is not supported")); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { listIterator.add("a"); - // We shouldn't get to here. - fail("add(Object) should throw an UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // This is correct; ignore the exception. - } + }); + assertTrue(exception.getMessage().contains("add() is not supported")); listIterator.next(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { listIterator.remove(); - // We shouldn't get to here. - fail("remove() should throw an UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // This is correct; ignore the exception. - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { listIterator.set("a"); - // We shouldn't get to here. - fail("set(Object) should throw an UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // This is correct; ignore the exception. - } + }); + assertTrue(exception.getMessage().contains("set() is not supported")); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { listIterator.add("a"); - // We shouldn't get to here. - fail("add(Object) should throw an UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // This is correct; ignore the exception. - } + }); + assertTrue(exception.getMessage().contains("add() is not supported")); } /** @@ -1411,7 +1275,7 @@ public void testUnmodifiableListIteratorIteration() { public void testUnmodifiableMapIterator() { final Set set = new LinkedHashSet<>(); final MapIterator ie = new EntrySetToMapIteratorAdapter(set); - assertTrue("create instance fail", IteratorUtils.unmodifiableMapIterator(ie) instanceof MapIterator); + assertTrue(IteratorUtils.unmodifiableMapIterator(ie) instanceof MapIterator); IteratorUtils.unmodifiableMapIterator(null); } @@ -1420,7 +1284,7 @@ public void testUnmodifiableMapIterator() { public void testZippingIterator() { final ArrayList arrayList = new ArrayList(); final Iterator ie = arrayList.iterator(); - assertTrue("create instance fail", IteratorUtils.zippingIterator(ie, ie, ie) instanceof ZippingIterator); - assertTrue("create instance fail", IteratorUtils.zippingIterator(ie, ie) instanceof ZippingIterator); + assertTrue(IteratorUtils.zippingIterator(ie, ie, ie) instanceof ZippingIterator); + assertTrue(IteratorUtils.zippingIterator(ie, ie) instanceof ZippingIterator); } } diff --git a/src/test/java/org/apache/commons/collections4/ListUtilsTest.java b/src/test/java/org/apache/commons/collections4/ListUtilsTest.java index 1a375b1830..2945cb3124 100644 --- a/src/test/java/org/apache/commons/collections4/ListUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/ListUtilsTest.java @@ -16,7 +16,14 @@ */ package org.apache.commons.collections4; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; @@ -58,7 +65,7 @@ public void setUp() { @Test public void testIntersectNonEmptyWithEmptyList() { final List empty = Collections.emptyList(); - assertTrue("result not empty", ListUtils.intersection(empty, fullList).isEmpty()); + assertTrue(ListUtils.intersection(empty, fullList).isEmpty()); } /** @@ -67,7 +74,7 @@ public void testIntersectNonEmptyWithEmptyList() { @Test public void testIntersectEmptyWithEmptyList() { final List empty = Collections.EMPTY_LIST; - assertTrue("result not empty", ListUtils.intersection(empty, empty).isEmpty()); + assertTrue(ListUtils.intersection(empty, empty).isEmpty()); } /** @@ -124,19 +131,16 @@ public void testIntersectionOrderInsensitivity() { public void testPredicatedList() { final Predicate predicate = o -> o instanceof String; final List list = ListUtils.predicatedList(new ArrayList<>(), predicate); - assertTrue("returned object should be a PredicatedList", list instanceof PredicatedList); - try { + assertTrue(list instanceof PredicatedList); + Exception exception = assertThrows(NullPointerException.class, () -> { ListUtils.predicatedList(new ArrayList<>(), null); - fail("Expecting IllegalArgumentException for null predicate."); - } catch (final NullPointerException ex) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("predicate")); + + exception = assertThrows(NullPointerException.class, () -> { ListUtils.predicatedList(null, predicate); - fail("Expecting IllegalArgumentException for null list."); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("collection")); } @Test @@ -242,10 +246,11 @@ public void testRetainAll() { fullList.retainAll(sub); assertEquals(retained, fullList); - try { + // this is what we want + Exception exception = assertThrows(NullPointerException.class, () -> { ListUtils.retainAll(null, null); - fail("expecting NullPointerException"); - } catch(final NullPointerException npe){} // this is what we want + }); + assertNull(exception.getMessage()); } @Test @@ -260,10 +265,11 @@ public void testRemoveAll() { fullList.removeAll(sub); assertEquals(remainder, fullList); - try { + // this is what we want + Exception exception = assertThrows(NullPointerException.class, () -> { ListUtils.removeAll(null, null); - fail("expecting NullPointerException"); - } catch(final NullPointerException npe) {} // this is what we want + }); + assertNull(exception.getMessage()); } @Test @@ -287,10 +293,11 @@ public void testSubtract() { assertEquals(expected, result); - try { + // this is what we want + Exception exception = assertThrows(NullPointerException.class, () -> { ListUtils.subtract(list, null); - fail("expecting NullPointerException"); - } catch(final NullPointerException npe) {} // this is what we want + }); + assertNull(exception.getMessage()); } @Test @@ -335,21 +342,20 @@ public void testIndexOf() { @Test @SuppressWarnings("boxing") // OK in test code public void testLongestCommonSubsequence() { - - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ListUtils.longestCommonSubsequence((List) null, null); - fail("failed to check for null argument"); - } catch (final NullPointerException e) {} + }); + assertTrue(exception.getMessage().contains("listA")); - try { + exception = assertThrows(NullPointerException.class, () -> { ListUtils.longestCommonSubsequence(Arrays.asList('A'), null); - fail("failed to check for null argument"); - } catch (final NullPointerException e) {} + }); + assertTrue(exception.getMessage().contains("listB")); - try { + exception = assertThrows(NullPointerException.class, () -> { ListUtils.longestCommonSubsequence(null, Arrays.asList('A')); - fail("failed to check for null argument"); - } catch (final NullPointerException e) {} + }); + assertTrue(exception.getMessage().contains("listA")); @SuppressWarnings("unchecked") List lcs = ListUtils.longestCommonSubsequence(Collections.EMPTY_LIST, Collections.EMPTY_LIST); @@ -376,21 +382,20 @@ public void testLongestCommonSubsequence() { @Test public void testLongestCommonSubsequenceWithString() { - - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ListUtils.longestCommonSubsequence((String) null, null); - fail("failed to check for null argument"); - } catch (final NullPointerException e) {} + }); + assertTrue(exception.getMessage().contains("charSequenceA")); - try { + exception = assertThrows(NullPointerException.class, () -> { ListUtils.longestCommonSubsequence("A", null); - fail("failed to check for null argument"); - } catch (final NullPointerException e) {} + }); + assertTrue(exception.getMessage().contains("charSequenceB")); - try { + exception = assertThrows(NullPointerException.class, () -> { ListUtils.longestCommonSubsequence(null, "A"); - fail("failed to check for null argument"); - } catch (final NullPointerException e) {} + }); + assertTrue(exception.getMessage().contains("charSequenceA")); String lcs = ListUtils.longestCommonSubsequence("", ""); assertEquals(0, lcs.length()); @@ -426,20 +431,20 @@ public void testPartition() { assertEquals(3, partition.size()); assertEquals(1, partition.get(2).size()); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ListUtils.partition(null, 3); - fail("failed to check for null argument"); - } catch (final NullPointerException e) {} + }); + assertTrue(exception.getMessage().contains("list")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { ListUtils.partition(strings, 0); - fail("failed to check for size argument"); - } catch (final IllegalArgumentException e) {} + }); + assertTrue(exception.getMessage().contains("Size must be greater than 0")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { ListUtils.partition(strings, -10); - fail("failed to check for size argument"); - } catch (final IllegalArgumentException e) {} + }); + assertTrue(exception.getMessage().contains("Size must be greater than 0")); final List> partitionMax = ListUtils.partition(strings, Integer.MAX_VALUE); assertEquals(1, partitionMax.size()); diff --git a/src/test/java/org/apache/commons/collections4/MapUtilsTest.java b/src/test/java/org/apache/commons/collections4/MapUtilsTest.java index 1703bcf979..725501c1f8 100644 --- a/src/test/java/org/apache/commons/collections4/MapUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/MapUtilsTest.java @@ -22,7 +22,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.ByteArrayOutputStream; @@ -69,12 +68,10 @@ public void testPredicatedMap() { final Predicate p = getPredicate(); final Map map = MapUtils.predicatedMap(new HashMap<>(), p, p); assertTrue(map instanceof PredicatedMap); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { MapUtils.predicatedMap(null, p, p); - fail("Expecting NullPointerException for null map."); - } catch (final NullPointerException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("map")); } @Test @@ -82,33 +79,28 @@ public void testLazyMapFactory() { final Factory factory = FactoryUtils.constantFactory(Integer.valueOf(5)); Map map = MapUtils.lazyMap(new HashMap<>(), factory); assertTrue(map instanceof LazyMap); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { MapUtils.lazyMap(new HashMap<>(), (Factory) null); - fail("Expecting NullPointerException for null factory"); - } catch (final NullPointerException e) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("factory")); + + exception = assertThrows(NullPointerException.class, () -> { MapUtils.lazyMap((Map) null, factory); - fail("Expecting NullPointerException for null map"); - } catch (final NullPointerException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("map")); + final Transformer transformer = TransformerUtils.asTransformer(factory); map = MapUtils.lazyMap(new HashMap<>(), transformer); assertTrue(map instanceof LazyMap); - try { + exception = assertThrows(NullPointerException.class, () -> { MapUtils.lazyMap(new HashMap<>(), (Transformer) null); - fail("Expecting NullPointerException for null transformer"); - } catch (final NullPointerException e) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("factory")); + + exception = assertThrows(NullPointerException.class, () -> { MapUtils.lazyMap((Map) null, transformer); - fail("Expecting NullPointerException for null map"); - } catch (final NullPointerException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("map")); } @Test @@ -176,14 +168,15 @@ public void testInvertMapNull() { @Test public void testPutAll_Map_array() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { MapUtils.putAll(null, null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("map")); + + exception = assertThrows(NullPointerException.class, () -> { MapUtils.putAll(null, new Object[0]); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("map")); Map test = MapUtils.putAll(new HashMap(), new String[0]); assertEquals(0, test.size()); @@ -202,32 +195,32 @@ public void testPutAll_Map_array() { assertEquals("#0000FF", test.get("BLUE")); assertEquals(3, test.size()); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { MapUtils.putAll(new HashMap(), new String[][] { {"RED", "#FF0000"}, null, {"BLUE", "#0000FF"} }); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + assertTrue(exception.getMessage().contains("Invalid array element: 1")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { MapUtils.putAll(new HashMap(), new String[][] { {"RED", "#FF0000"}, {"GREEN"}, {"BLUE", "#0000FF"} }); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + assertTrue(exception.getMessage().contains("Invalid array element: 1")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { MapUtils.putAll(new HashMap(), new String[][] { {"RED", "#FF0000"}, {}, {"BLUE", "#0000FF"} }); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + assertTrue(exception.getMessage().contains("Invalid array element: 1")); // flat array test = MapUtils.putAll(new HashMap(), new String[] { @@ -333,11 +326,7 @@ public void testDebugAndVerbosePrintCasting() { final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream outPrint = new PrintStream(out); - try { - MapUtils.debugPrint(outPrint, "Print Map", outer); - } catch (final ClassCastException e) { - fail("No Casting should be occurring!"); - } + MapUtils.debugPrint(outPrint, "Print Map", outer); } @Test @@ -436,20 +425,18 @@ public void testDebugPrintNullLabelAndMap() { @Test public void testVerbosePrintNullStream() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { MapUtils.verbosePrint(null, "Map", new HashMap<>()); - fail("Should generate NullPointerException"); - } catch (final NullPointerException expected) { - } + }); + assertNull(exception.getMessage()); } @Test public void testDebugPrintNullStream() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { MapUtils.debugPrint(null, "Map", new HashMap<>()); - fail("Should generate NullPointerException"); - } catch (final NullPointerException expected) { - } + }); + assertNull(exception.getMessage()); } @Test @@ -874,11 +861,11 @@ public void testPopulateMultiMap() { @Test public void testIterableMap() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { MapUtils.iterableMap(null); - fail("Should throw NullPointerException"); - } catch (final NullPointerException e) { - } + }); + assertTrue(exception.getMessage().contains("map")); + final HashMap map = new HashMap<>(); map.put("foo", "foov"); map.put("bar", "barv"); @@ -892,11 +879,11 @@ public void testIterableMap() { @Test public void testIterableSortedMap() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { MapUtils.iterableSortedMap(null); - fail("Should throw NullPointerException"); - } catch (final NullPointerException e) { - } + }); + assertTrue(exception.getMessage().contains("sortedMap")); + final TreeMap map = new TreeMap<>(); map.put("foo", "foov"); map.put("bar", "barv"); diff --git a/src/test/java/org/apache/commons/collections4/MultiMapUtilsTest.java b/src/test/java/org/apache/commons/collections4/MultiMapUtilsTest.java index fca91233b0..290b54b8c3 100644 --- a/src/test/java/org/apache/commons/collections4/MultiMapUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/MultiMapUtilsTest.java @@ -18,9 +18,9 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Collection; @@ -43,22 +43,20 @@ public class MultiMapUtilsTest { public void testEmptyUnmodifiableMultiValuedMap() { final MultiValuedMap map = MultiMapUtils.EMPTY_MULTI_VALUED_MAP; assertTrue(map.isEmpty()); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { map.put("key", "value"); - fail("Should throw UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); } @Test public void testTypeSafeEmptyMultiValuedMap() { final MultiValuedMap map = MultiMapUtils.emptyMultiValuedMap(); assertTrue(map.isEmpty()); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { map.put("key", "value"); - fail("Should throw UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); } @Test diff --git a/src/test/java/org/apache/commons/collections4/MultiSetUtilsTest.java b/src/test/java/org/apache/commons/collections4/MultiSetUtilsTest.java index 85c07affb7..aef137e63b 100644 --- a/src/test/java/org/apache/commons/collections4/MultiSetUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/MultiSetUtilsTest.java @@ -17,7 +17,9 @@ package org.apache.commons.collections4; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; @@ -49,11 +51,11 @@ public void setUp() { public void testEmptyMultiSet() { final MultiSet empty = MultiSetUtils.emptyMultiSet(); assertEquals(0, empty.size()); - try { + + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { empty.add(55); - fail("Empty multi set must be read-only"); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); } /** @@ -64,17 +66,15 @@ public void testUnmodifiableMultiSet() { final MultiSet unmodifiable = MultiSetUtils.unmodifiableMultiSet(multiSet); assertEquals(multiSet, unmodifiable); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { unmodifiable.add("a"); - fail("Empty multi set must be read-only"); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(NullPointerException.class, () -> { MultiSetUtils.unmodifiableMultiSet(null); - fail("Expecting NPE"); - } catch (final NullPointerException e) { - } + }); + assertTrue(exception.getMessage().contains("collection")); } /** @@ -97,22 +97,19 @@ public void testPredicatedMultiSet() { assertEquals(multiSet.size(), predicated.size()); assertEquals(multiSet.getCount("a"), predicated.getCount("a")); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { MultiSetUtils.predicatedMultiSet(null, predicate); - fail("Expecting NPE"); - } catch (final NullPointerException e) { - } + }); + assertTrue(exception.getMessage().contains("collection")); - try { + exception = assertThrows(NullPointerException.class, () -> { MultiSetUtils.predicatedMultiSet(multiSet, null); - fail("Expecting NPE"); - } catch (final NullPointerException e) { - } + }); + assertTrue(exception.getMessage().contains("predicate")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { MultiSetUtils.predicatedMultiSet(multiSet, object -> object.equals("a")); - fail("Predicate is violated for all elements not being 'a'"); - } catch (final IllegalArgumentException iae) { - } + }); + assertTrue(exception.getMessage().contains("Cannot add Object 'b' - Predicate")); } } diff --git a/src/test/java/org/apache/commons/collections4/PredicateUtilsTest.java b/src/test/java/org/apache/commons/collections4/PredicateUtilsTest.java index 5cb497188d..141c211531 100644 --- a/src/test/java/org/apache/commons/collections4/PredicateUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/PredicateUtilsTest.java @@ -18,7 +18,11 @@ import static org.apache.commons.collections4.functors.NullPredicate.*; import static org.apache.commons.collections4.functors.TruePredicate.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; @@ -56,13 +60,11 @@ public void testExceptionPredicate() { try { PredicateUtils.exceptionPredicate().evaluate(null); } catch (final FunctorException ex) { - try { + Exception exception = assertThrows(FunctorException.class, () -> { PredicateUtils.exceptionPredicate().evaluate(cString); - } catch (final FunctorException ex2) { - return; - } + }); + assertTrue(exception.getMessage().contains("ExceptionPredicate invoked")); } - fail(); } // notNullPredicate @@ -660,10 +662,10 @@ public void testTransformedPredicate() { final Predicate p = EqualPredicate.equalPredicate("Hello"); assertFalse(PredicateUtils.transformedPredicate(t, p).evaluate(null)); assertTrue(PredicateUtils.transformedPredicate(t, p).evaluate(Boolean.TRUE)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { PredicateUtils.transformedPredicate(null, null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("transformer")); } // misc tests diff --git a/src/test/java/org/apache/commons/collections4/QueueUtilsTest.java b/src/test/java/org/apache/commons/collections4/QueueUtilsTest.java index 8842ff7f82..3bb31a3d87 100644 --- a/src/test/java/org/apache/commons/collections4/QueueUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/QueueUtilsTest.java @@ -17,8 +17,9 @@ package org.apache.commons.collections4; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.LinkedList; import java.util.Queue; @@ -44,25 +45,21 @@ public class QueueUtilsTest { @Test public void testSynchronizedQueue() { final Queue queue = QueueUtils.synchronizedQueue(new LinkedList<>()); - assertTrue("Returned object should be a SynchronizedQueue.", queue instanceof SynchronizedQueue); - try { + assertTrue(queue instanceof SynchronizedQueue); + Exception exception = assertThrows(NullPointerException.class, () -> { QueueUtils.synchronizedQueue(null); - fail("Expecting NullPointerException for null queue."); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("collection")); } @Test public void testUnmodifiableQueue() { final Queue queue = QueueUtils.unmodifiableQueue(new LinkedList<>()); - assertTrue("Returned object should be an UnmodifiableQueue.", queue instanceof UnmodifiableQueue); - try { + assertTrue(queue instanceof UnmodifiableQueue); + Exception exception = assertThrows(NullPointerException.class, () -> { QueueUtils.unmodifiableQueue(null); - fail("Expecting NullPointerException for null queue."); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("collection")); assertSame("UnmodifiableQueue shall not be decorated", queue, QueueUtils.unmodifiableQueue(queue)); } @@ -70,51 +67,42 @@ public void testUnmodifiableQueue() { @Test public void testPredicatedQueue() { final Queue queue = QueueUtils.predicatedQueue(new LinkedList<>(), truePredicate); - assertTrue("Returned object should be a PredicatedQueue.", queue instanceof PredicatedQueue); - try { + assertTrue( queue instanceof PredicatedQueue); + Exception exception = assertThrows(NullPointerException.class, () -> { QueueUtils.predicatedQueue(null, truePredicate); - fail("Expecting NullPointerException for null queue."); - } catch (final NullPointerException ex) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("collection")); + + exception = assertThrows(NullPointerException.class, () -> { QueueUtils.predicatedQueue(new LinkedList<>(), null); - fail("Expecting NullPointerException for null predicate."); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test public void testTransformedQueue() { final Queue queue = QueueUtils.transformingQueue(new LinkedList<>(), nopTransformer); - assertTrue("Returned object should be an TransformedQueue.", queue instanceof TransformedQueue); - try { + assertTrue(queue instanceof TransformedQueue); + Exception exception = assertThrows(NullPointerException.class, () -> { QueueUtils.transformingQueue(null, nopTransformer); - fail("Expecting NullPointerException for null queue."); - } catch (final NullPointerException ex) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("collection")); + + exception = assertThrows(NullPointerException.class, () -> { QueueUtils.transformingQueue(new LinkedList<>(), null); - fail("Expecting NullPointerException for null transformer."); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("transformer")); } @Test public void testEmptyQueue() { final Queue queue = QueueUtils.emptyQueue(); - assertTrue("Returned object should be an UnmodifiableQueue.", queue instanceof UnmodifiableQueue); - assertTrue("Returned queue is not empty.", queue.isEmpty()); + assertTrue(queue instanceof UnmodifiableQueue); + assertTrue(queue.isEmpty()); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { queue.add(new Object()); - fail("Expecting UnsupportedOperationException for empty queue."); - } catch (final UnsupportedOperationException ex) { - // expected - } + }); + assertNull(exception.getMessage()); } - } diff --git a/src/test/java/org/apache/commons/collections4/SetUtilsTest.java b/src/test/java/org/apache/commons/collections4/SetUtilsTest.java index 7936129f65..f4b951d51d 100644 --- a/src/test/java/org/apache/commons/collections4/SetUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/SetUtilsTest.java @@ -19,10 +19,10 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Collection; @@ -56,19 +56,15 @@ public void difference() { final Set set2 = SetUtils.difference(setA, SetUtils.emptySet()); assertEquals(setA, set2); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { SetUtils.difference(setA, null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("set")); - try { + exception = assertThrows(NullPointerException.class, () -> { SetUtils.difference(null, setA); - fail("Expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("set")); } @Test @@ -86,19 +82,15 @@ public void disjunction() { final Set set2 = SetUtils.disjunction(setA, SetUtils.emptySet()); assertEquals(setA, set2); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { SetUtils.disjunction(setA, null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("set")); - try { + exception = assertThrows(NullPointerException.class, () -> { SetUtils.disjunction(null, setA); - fail("Expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("set")); } @Test @@ -116,19 +108,15 @@ public void intersection() { final Set set2 = SetUtils.intersection(setA, SetUtils.emptySet()); assertEquals(SetUtils.emptySet(), set2); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { SetUtils.intersection(setA, null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("set")); - try { + exception = assertThrows(NullPointerException.class, () -> { SetUtils.intersection(null, setA); - fail("Expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("set")); } @Before @@ -191,26 +179,26 @@ public void testHashCode() { @Test public void testHashSet() { final Set set1 = SetUtils.unmodifiableSet(); - assertTrue("set is empty", set1.isEmpty()); + assertTrue(set1.isEmpty()); final Set set2 = SetUtils.hashSet(1, 2, 2, 3); assertEquals("set has 3 elements", 3, set2.size()); - assertTrue("set contains 1", set2.contains(1)); - assertTrue("set contains 2", set2.contains(2)); - assertTrue("set contains 3", set2.contains(3)); + assertTrue(set2.contains(1)); + assertTrue(set2.contains(2)); + assertTrue(set2.contains(3)); final Set set3 = SetUtils.hashSet("1", "2", "2", "3"); assertEquals("set has 3 elements", 3, set3.size()); - assertTrue("set contains 1", set3.contains("1")); - assertTrue("set contains 2", set3.contains("2")); - assertTrue("set contains 3", set3.contains("3")); + assertTrue(set3.contains("1")); + assertTrue(set3.contains("2")); + assertTrue(set3.contains("3")); final Set set4 = SetUtils.hashSet(null, null); assertEquals("set has 1 element", 1, set4.size()); - assertTrue("set contains null", set4.contains(null)); + assertTrue(set4.contains(null)); final Set set5 = SetUtils.hashSet((Object[]) null); - assertNull("set is null", set5); + assertNull(set5); } @Test @@ -234,44 +222,41 @@ public void testNewIdentityHashSet() { public void testpredicatedSet() { final Predicate predicate = o -> o instanceof String; final Set set = SetUtils.predicatedSet(new HashSet<>(), predicate); - assertTrue("returned object should be a PredicatedSet", set instanceof PredicatedSet); - try { + assertTrue(set instanceof PredicatedSet); + Exception exception = assertThrows(NullPointerException.class, () -> { SetUtils.predicatedSet(new HashSet<>(), null); - fail("Expecting NullPointerException for null predicate."); - } catch (final NullPointerException ex) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("predicate")); + + exception = assertThrows(NullPointerException.class, () -> { SetUtils.predicatedSet(null, predicate); - fail("Expecting NullPointerException for null set."); - } catch (final NullPointerException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("collection")); } @Test public void testUnmodifiableSet() { final Set set1 = SetUtils.unmodifiableSet(); - assertTrue("set is empty", set1.isEmpty()); + assertTrue(set1.isEmpty()); final Set set2 = SetUtils.unmodifiableSet(1, 2, 2, 3); assertEquals("set has 3 elements", 3, set2.size()); - assertTrue("set contains 1", set2.contains(1)); - assertTrue("set contains 2", set2.contains(2)); - assertTrue("set contains 3", set2.contains(3)); + assertTrue(set2.contains(1)); + assertTrue(set2.contains(2)); + assertTrue(set2.contains(3)); final Set set3 = SetUtils.unmodifiableSet("1", "2", "2", "3"); assertEquals("set has 3 elements", 3, set3.size()); - assertTrue("set contains 1", set3.contains("1")); - assertTrue("set contains 2", set3.contains("2")); - assertTrue("set contains 3", set3.contains("3")); + assertTrue(set3.contains("1")); + assertTrue(set3.contains("2")); + assertTrue(set3.contains("3")); final Set set4 = SetUtils.unmodifiableSet(null, null); assertEquals("set has 1 element", 1, set4.size()); - assertTrue("set contains null", set4.contains(null)); + assertTrue( set4.contains(null)); final Set set5 = SetUtils.unmodifiableSet((Object[]) null); - assertNull("set is null", set5); + assertNull(set5); } @Test @@ -291,19 +276,15 @@ public void union() { final Set set2 = SetUtils.union(setA, SetUtils.emptySet()); assertEquals(setA, set2); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { SetUtils.union(setA, null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("setB")); - try { + exception = assertThrows(NullPointerException.class, () -> { SetUtils.union(null, setA); - fail("Expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("setA")); } } diff --git a/src/test/java/org/apache/commons/collections4/SplitMapUtilsTest.java b/src/test/java/org/apache/commons/collections4/SplitMapUtilsTest.java index 2359be0a6c..9ea805cc90 100644 --- a/src/test/java/org/apache/commons/collections4/SplitMapUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/SplitMapUtilsTest.java @@ -20,7 +20,8 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.HashMap; import java.util.Map; @@ -165,11 +166,9 @@ private void attemptPutOperation(final Runnable r) { } private void attemptMapOperation(final String s, final Runnable r) { - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { r.run(); - fail(s); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); } - } diff --git a/src/test/java/org/apache/commons/collections4/TransformerUtilsTest.java b/src/test/java/org/apache/commons/collections4/TransformerUtilsTest.java index 196d74cd5c..6a734357b2 100644 --- a/src/test/java/org/apache/commons/collections4/TransformerUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/TransformerUtilsTest.java @@ -18,9 +18,10 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Collection; @@ -60,13 +61,11 @@ public void testExceptionTransformer() { try { TransformerUtils.exceptionTransformer().transform(null); } catch (final FunctorException ex) { - try { + Exception exception = assertThrows(FunctorException.class, () -> { TransformerUtils.exceptionTransformer().transform(cString); - } catch (final FunctorException ex2) { - return; - } + }); + assertTrue(exception.getMessage().contains("ExceptionTransformer invoked")); } - fail(); } // nullTransformer @@ -115,12 +114,10 @@ public void testCloneTransformer() { assertNull(TransformerUtils.cloneTransformer().transform(null)); assertEquals(cString, TransformerUtils.cloneTransformer().transform(cString)); assertEquals(cInteger, TransformerUtils.cloneTransformer().transform(cInteger)); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { assertEquals(cObject, TransformerUtils.cloneTransformer().transform(cObject)); - } catch (final IllegalArgumentException ex) { - return; - } - fail(); + }); + assertTrue(exception.getMessage().contains("The prototype must be cloneable via a public clone method")); } // mapTransformer @@ -149,12 +146,10 @@ public void testExecutorTransformer() { assertEquals(cObject, TransformerUtils.asTransformer(ClosureUtils.nopClosure()).transform(cObject)); assertEquals(cString, TransformerUtils.asTransformer(ClosureUtils.nopClosure()).transform(cString)); assertEquals(cInteger, TransformerUtils.asTransformer(ClosureUtils.nopClosure()).transform(cInteger)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.asTransformer((Closure) null); - } catch (final NullPointerException ex) { - return; - } - fail(); + }); + assertTrue(exception.getMessage().contains("closure")); } // predicateTransformer @@ -166,12 +161,10 @@ public void testPredicateTransformer() { assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(TruePredicate.truePredicate()).transform(cObject)); assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(TruePredicate.truePredicate()).transform(cString)); assertEquals(Boolean.TRUE, TransformerUtils.asTransformer(TruePredicate.truePredicate()).transform(cInteger)); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { TransformerUtils.asTransformer((Predicate) null); - } catch (final IllegalArgumentException ex) { - return; - } - fail(); + }); + assertTrue(exception.getMessage().contains("Predicate must not be null")); } // factoryTransformer @@ -183,12 +176,10 @@ public void testFactoryTransformer() { assertNull(TransformerUtils.asTransformer(FactoryUtils.nullFactory()).transform(cObject)); assertNull(TransformerUtils.asTransformer(FactoryUtils.nullFactory()).transform(cString)); assertNull(TransformerUtils.asTransformer(FactoryUtils.nullFactory()).transform(cInteger)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.asTransformer((Factory) null); - } catch (final NullPointerException ex) { - return; - } - fail(); + }); + assertTrue(exception.getMessage().contains("factory")); } // chainedTransformer @@ -211,29 +202,33 @@ public void testChainedTransformer() { assertSame(NOPTransformer.INSTANCE, TransformerUtils.chainedTransformer()); assertSame(NOPTransformer.INSTANCE, TransformerUtils.chainedTransformer(Collections.>emptyList())); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.chainedTransformer(null, null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("transformers[0]")); + + exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.chainedTransformer((Transformer[]) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("transformers")); + + exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.chainedTransformer((Collection>) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("transformers")); + + exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.chainedTransformer(null, null); - fail(); - } catch (final NullPointerException ex) {} - try { - coll = new ArrayList<>(); - coll.add(null); - coll.add(null); - TransformerUtils.chainedTransformer(coll); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("transformers[0]")); + + final Collection> collection = new ArrayList<>(); + collection.add(null); + collection.add(null); + exception = assertThrows(NullPointerException.class, () -> { + TransformerUtils.chainedTransformer(collection); + }); + assertTrue(exception.getMessage().contains("transformers[0]")); } // ifTransformer @@ -258,22 +253,25 @@ public void testIfTransformer() { assertEquals("C", TransformerUtils.ifTransformer(equalsAPredicate, c).transform("A")); assertEquals("B", TransformerUtils.ifTransformer(equalsAPredicate, c).transform("B")); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.ifTransformer(null, null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("predicate")); + + exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.ifTransformer(TruePredicate.truePredicate(), null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("trueTransformer")); + + exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.ifTransformer(null, ConstantTransformer.constantTransformer("A")); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("predicate")); + + exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.ifTransformer(null, null, null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("predicate")); } // switchTransformer @@ -318,28 +316,32 @@ public void testSwitchTransformer() { map.put(null, null); assertEquals(ConstantTransformer.NULL_INSTANCE, TransformerUtils.switchTransformer(map)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.switchTransformer(null, null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("predicates")); + + exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.switchTransformer(null, (Transformer[]) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("predicates")); + + exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.switchTransformer(null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("map")); + + exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.switchTransformer(new Predicate[2], new Transformer[2]); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("predicates[0]")); + + exception = assertThrows(IllegalArgumentException.class, () -> { TransformerUtils.switchTransformer( new Predicate[] { TruePredicate.truePredicate() }, new Transformer[] { a, b }); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + assertTrue(exception.getMessage().contains("The predicate and transformer arrays must be the same size")); } // switchMapTransformer @@ -365,10 +367,10 @@ public void testSwitchMapTransformer() { map.put(null, null); assertSame(ConstantTransformer.NULL_INSTANCE, TransformerUtils.switchMapTransformer(map)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.switchMapTransformer(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("objectsAndTransformers")); } // invokerTransformer @@ -382,14 +384,15 @@ public void testInvokerTransformer() { assertEquals(1, TransformerUtils.invokerTransformer("size").transform(list)); assertNull(TransformerUtils.invokerTransformer("size").transform(null)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.invokerTransformer(null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("methodName")); + + exception = assertThrows(FunctorException.class, () -> { TransformerUtils.invokerTransformer("noSuchMethod").transform(new Object()); - fail(); - } catch (final FunctorException ex) {} + }); + assertTrue(exception.getMessage().contains("InvokerTransformer: The method 'noSuchMethod' on 'class java.lang.Object' does not exist")); } // invokerTransformer2 @@ -406,27 +409,31 @@ public void testInvokerTransformer2() { assertNull(TransformerUtils.invokerTransformer("contains", new Class[]{Object.class}, new Object[]{cString}).transform(null)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { TransformerUtils.invokerTransformer(null, null, null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("methodName")); + + exception = assertThrows(FunctorException.class, () -> { TransformerUtils.invokerTransformer("noSuchMethod", new Class[] { Object.class }, new Object[] { cString }).transform(new Object()); - fail(); - } catch (final FunctorException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("InvokerTransformer: The method 'noSuchMethod' on 'class java.lang.Object' does not exist")); + + exception = assertThrows(IllegalArgumentException.class, () -> { TransformerUtils.invokerTransformer("badArgs", null, new Object[] { cString }); - fail(); - } catch (final IllegalArgumentException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("The parameter types must match the arguments")); + + exception = assertThrows(IllegalArgumentException.class, () -> { TransformerUtils.invokerTransformer("badArgs", new Class[] { Object.class }, null); - fail(); - } catch (final IllegalArgumentException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("The parameter types must match the arguments")); + + exception = assertThrows(IllegalArgumentException.class, () -> { TransformerUtils.invokerTransformer("badArgs", new Class[] {}, new Object[] { cString }); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + assertTrue(exception.getMessage().contains("The parameter types must match the arguments")); } // stringValueTransformer @@ -447,22 +454,24 @@ public void testStringValueTransformer() { @Test public void testInstantiateTransformerNull() { - try { + + Exception exception = assertThrows(IllegalArgumentException.class, () -> { TransformerUtils.instantiateTransformer(null, new Object[] { "str" }); - fail(); - } catch (final IllegalArgumentException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("Parameter types must match the arguments")); + + exception = assertThrows(IllegalArgumentException.class, () -> { TransformerUtils.instantiateTransformer(new Class[] {}, new Object[] { "str" }); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + assertTrue(exception.getMessage().contains("Parameter types must match the arguments")); - Transformer, Object> trans = TransformerUtils.instantiateTransformer(new Class[] { Long.class }, new Object[] { null }); - try { - trans.transform(String.class); - fail(); - } catch (final FunctorException ex) {} + final Transformer, Object> transformer = TransformerUtils.instantiateTransformer(new Class[] { Long.class }, new Object[] { null }); + exception = assertThrows(FunctorException.class, () -> { + transformer.transform(String.class); + }); + assertTrue(exception.getMessage().contains("InstantiateTransformer: The constructor must exist and be public")); - trans = TransformerUtils.instantiateTransformer(); + Transformer, Object> trans = TransformerUtils.instantiateTransformer(); assertEquals("", trans.transform(String.class)); trans = TransformerUtils.instantiateTransformer(new Class[] { Long.TYPE }, new Object[] {1000L}); diff --git a/src/test/java/org/apache/commons/collections4/TrieUtilsTest.java b/src/test/java/org/apache/commons/collections4/TrieUtilsTest.java index 1c78852795..57377de0b0 100644 --- a/src/test/java/org/apache/commons/collections4/TrieUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/TrieUtilsTest.java @@ -16,7 +16,9 @@ */ package org.apache.commons.collections4; -import static org.junit.Assert.*; +import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import org.apache.commons.collections4.trie.PatriciaTrie; import org.apache.commons.collections4.trie.UnmodifiableTrie; @@ -33,14 +35,12 @@ public class TrieUtilsTest { @Test public void testUnmodifiableTrie() { final Trie trie = TrieUtils.unmodifiableTrie(new PatriciaTrie<>()); - assertTrue("Returned object should be an UnmodifiableTrie.", - trie instanceof UnmodifiableTrie); - try { + assertTrue(trie instanceof UnmodifiableTrie); + Exception exception = assertThrows(NullPointerException.class, () -> { TrieUtils.unmodifiableTrie(null); - fail("Expecting NullPointerException for null trie."); - } catch (final NullPointerException ex) { - // expected - } + }); + String actualMessage = exception.getMessage(); + assertTrue(actualMessage.contains("trie")); assertSame("UnmodifiableTrie shall not be decorated", trie, TrieUtils.unmodifiableTrie(trie)); } diff --git a/src/test/java/org/apache/commons/collections4/bag/AbstractBagTest.java b/src/test/java/org/apache/commons/collections4/bag/AbstractBagTest.java index 969280dfa7..5fb60281a0 100644 --- a/src/test/java/org/apache/commons/collections4/bag/AbstractBagTest.java +++ b/src/test/java/org/apache/commons/collections4/bag/AbstractBagTest.java @@ -34,6 +34,9 @@ import org.apache.commons.collections4.set.AbstractSetTest; import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Abstract test class for {@link org.apache.commons.collections4.Bag Bag} methods and contracts. @@ -383,12 +386,10 @@ public void testBagIteratorFail() { final Iterator it = bag.iterator(); it.next(); bag.remove("A"); - try { + Exception exception = assertThrows(ConcurrentModificationException.class, () -> { it.next(); - fail("Should throw ConcurrentModificationException"); - } catch (final ConcurrentModificationException e) { - // expected - } + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -405,12 +406,10 @@ public void testBagIteratorFailNoMore() { it.next(); it.next(); it.next(); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail("Should throw NoSuchElementException"); - } catch (final NoSuchElementException ex) { - // expected - } + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -429,12 +428,10 @@ public void testBagIteratorFailDoubleRemove() { assertEquals(3, bag.size()); it.remove(); assertEquals(2, bag.size()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail("Should throw IllegalStateException"); - } catch (final IllegalStateException ex) { - // expected - } + }); + assertNull(exception.getMessage()); assertEquals(2, bag.size()); it.next(); it.remove(); diff --git a/src/test/java/org/apache/commons/collections4/bag/PredicatedBagTest.java b/src/test/java/org/apache/commons/collections4/bag/PredicatedBagTest.java index 0aed058ff1..21c6fb45ba 100644 --- a/src/test/java/org/apache/commons/collections4/bag/PredicatedBagTest.java +++ b/src/test/java/org/apache/commons/collections4/bag/PredicatedBagTest.java @@ -16,6 +16,8 @@ */ package org.apache.commons.collections4.bag; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Set; import junit.framework.Test; @@ -85,12 +87,10 @@ public void testlegalAddRemove() { public void testIllegalAdd() { final Bag bag = makeTestBag(); final Integer i = 3; - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { bag.add((T) i); - fail("Integer should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3'")); assertFalse("Collection shouldn't contain illegal element", bag.contains(i)); } @@ -101,18 +101,14 @@ public void testIllegalDecorate() { elements.add("two"); elements.add(3); elements.add("four"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { decorateBag((HashBag) elements, stringPredicate()); - fail("Bag contains an element that should fail the predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3'")); + exception = assertThrows(NullPointerException.class, () -> { decorateBag(new HashBag(), null); - fail("Expecting NullPointerException for null predicate."); - } catch (final NullPointerException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Override diff --git a/src/test/java/org/apache/commons/collections4/bag/PredicatedSortedBagTest.java b/src/test/java/org/apache/commons/collections4/bag/PredicatedSortedBagTest.java index ae1e1608e3..9dc6070971 100644 --- a/src/test/java/org/apache/commons/collections4/bag/PredicatedSortedBagTest.java +++ b/src/test/java/org/apache/commons/collections4/bag/PredicatedSortedBagTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.bag; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Comparator; import junit.framework.Test; @@ -69,14 +72,14 @@ protected SortedBag makeTestBag() { public void testDecorate() { final SortedBag bag = decorateBag(new TreeBag(), stringPredicate()); ((PredicatedSortedBag) bag).decorated(); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { decorateBag(new TreeBag(), null); - fail("Expecting NullPointerException for null predicate"); - } catch (final NullPointerException e) {} - try { + }); + assertTrue(exception.getMessage().contains("predicate")); + exception = assertThrows(NullPointerException.class, () -> { decorateBag(nullBag, stringPredicate()); - fail("Expecting NullPointerException for null bag"); - } catch (final NullPointerException e) {} + }); + assertTrue(exception.getMessage().contains("collection")); } @SuppressWarnings("unchecked") diff --git a/src/test/java/org/apache/commons/collections4/bag/TreeBagTest.java b/src/test/java/org/apache/commons/collections4/bag/TreeBagTest.java index 136d747bc5..b3675154fc 100644 --- a/src/test/java/org/apache/commons/collections4/bag/TreeBagTest.java +++ b/src/test/java/org/apache/commons/collections4/bag/TreeBagTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.bag; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import junit.framework.Test; import org.apache.commons.collections4.Bag; @@ -56,33 +59,28 @@ public SortedBag setupBag() { public void testCollections265() { final Bag bag = new TreeBag<>(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { bag.add(new Object()); - fail("IllegalArgumentException expected"); - } catch(final IllegalArgumentException iae) { - // expected; - } + }); + assertTrue(exception.getMessage().contains( + "Objects of type class java.lang.Object cannot be added to a naturally ordered TreeBag as it does not implement Comparable")); } public void testCollections555() { final Bag bag = new TreeBag<>(); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { bag.add(null); - fail("NullPointerException expected"); - } catch(final NullPointerException npe) { - // expected; - } + }); + assertTrue(exception.getMessage().contains("object")); final Bag bag2 = new TreeBag<>(String::compareTo); - try { - // jdk bug: adding null to an empty TreeMap works - // thus ensure that the bag is not empty before adding null + // jdk bug: adding null to an empty TreeMap works + // thus ensure that the bag is not empty before adding null + exception = assertThrows(NullPointerException.class, () -> { bag2.add("a"); bag2.add(null); - fail("NullPointerException expected"); - } catch(final NullPointerException npe) { - // expected; - } + }); + assertNull(exception.getMessage()); } public void testOrdering() { diff --git a/src/test/java/org/apache/commons/collections4/bag/UnmodifiableBagTest.java b/src/test/java/org/apache/commons/collections4/bag/UnmodifiableBagTest.java index 9c781b010c..21faca4813 100644 --- a/src/test/java/org/apache/commons/collections4/bag/UnmodifiableBagTest.java +++ b/src/test/java/org/apache/commons/collections4/bag/UnmodifiableBagTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.bag; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import junit.framework.Test; @@ -85,10 +88,10 @@ public void testDecorateFactory() { final Bag queue = makeFullCollection(); assertSame(queue, UnmodifiableBag.unmodifiableBag(queue)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableBag.unmodifiableBag(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("collection")); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/bag/UnmodifiableSortedBagTest.java b/src/test/java/org/apache/commons/collections4/bag/UnmodifiableSortedBagTest.java index c481a19687..570b030b65 100644 --- a/src/test/java/org/apache/commons/collections4/bag/UnmodifiableSortedBagTest.java +++ b/src/test/java/org/apache/commons/collections4/bag/UnmodifiableSortedBagTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.bag; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import junit.framework.Test; @@ -85,10 +88,10 @@ public void testDecorateFactory() { final SortedBag queue = makeFullCollection(); assertSame(queue, UnmodifiableSortedBag.unmodifiableSortedBag(queue)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableSortedBag.unmodifiableSortedBag(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("collection")); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/bidimap/AbstractBidiMapTest.java b/src/test/java/org/apache/commons/collections4/bidimap/AbstractBidiMapTest.java index 2e5027009d..a37f737254 100644 --- a/src/test/java/org/apache/commons/collections4/bidimap/AbstractBidiMapTest.java +++ b/src/test/java/org/apache/commons/collections4/bidimap/AbstractBidiMapTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.bidimap; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Collection; import java.util.HashMap; import java.util.Iterator; @@ -206,45 +210,43 @@ private void modifyEntrySet(final BidiMap map) { newValue, map.get(key)); - assertNull( - "Modifying entrySet did not affect inverse Map.", - map.getKey(oldValue)); + assertNull(map.getKey(oldValue)); } //----------------------------------------------------------------------- public void testBidiClear() { if (!isRemoveSupported()) { - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { makeFullMap().clear(); - fail(); - } catch(final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); return; } BidiMap map = makeFullMap(); map.clear(); - assertTrue("Map was not cleared.", map.isEmpty()); - assertTrue("Inverse map was not cleared.", map.inverseBidiMap().isEmpty()); + assertTrue(map.isEmpty()); + assertTrue(map.inverseBidiMap().isEmpty()); // Tests clear on inverse map = makeFullMap().inverseBidiMap(); map.clear(); - assertTrue("Map was not cleared.", map.isEmpty()); - assertTrue("Inverse map was not cleared.", map.inverseBidiMap().isEmpty()); + assertTrue(map.isEmpty()); + assertTrue(map.inverseBidiMap().isEmpty()); } //----------------------------------------------------------------------- public void testBidiRemove() { if (!isRemoveSupported()) { - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { makeFullMap().remove(getSampleKeys()[0]); - fail(); - } catch(final UnsupportedOperationException ex) {} - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { makeFullMap().removeValue(getSampleValues()[0]); - fail(); - } catch(final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); return; } @@ -260,13 +262,13 @@ public void testBidiRemove() { private void remove(final BidiMap map, final Object key) { final Object value = map.remove(key); assertFalse("Key was not removed.", map.containsKey(key)); - assertNull("Value was not removed.", map.getKey(value)); + assertNull(map.getKey(value)); } private void removeValue(final BidiMap map, final Object value) { final Object key = map.removeValue(value); assertFalse("Key was not removed.", map.containsKey(key)); - assertNull("Value was not removed.", map.getKey(value)); + assertNull(map.getKey(value)); } //----------------------------------------------------------------------- @@ -537,10 +539,11 @@ public void testBidiMapIteratorSet() { final K key1 = it.next(); if (!isSetValueSupported()) { - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { it.setValue(newValue1); - fail(); - } catch (final UnsupportedOperationException ex) { + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("setValue() is not supported")); } return; } @@ -575,12 +578,14 @@ public void testBidiMapIteratorSet() { // at this point // key1=newValue1, key2=newValue2 - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { it.setValue(newValue1); // should remove key1 - fail(); - } catch (final IllegalArgumentException ex) { - return; // simplest way of dealing with tricky situation + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("Cannot use setValue() when the object being set is already in the map")); // simplest way of dealing with tricky situation + return; } + confirmed.put(key2, newValue1); AbstractBidiMapTest.this.getConfirmed().remove(key1); assertEquals(newValue1, it.getValue()); diff --git a/src/test/java/org/apache/commons/collections4/bidimap/AbstractOrderedBidiMapTest.java b/src/test/java/org/apache/commons/collections4/bidimap/AbstractOrderedBidiMapTest.java index b31f7b577f..4c4fa63d5d 100644 --- a/src/test/java/org/apache/commons/collections4/bidimap/AbstractOrderedBidiMapTest.java +++ b/src/test/java/org/apache/commons/collections4/bidimap/AbstractOrderedBidiMapTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.bidimap; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; @@ -45,28 +49,36 @@ public AbstractOrderedBidiMapTest() { //----------------------------------------------------------------------- public void testFirstKey() { resetEmpty(); - OrderedBidiMap bidi = getMap(); - try { - bidi.firstKey(); - fail(); - } catch (final NoSuchElementException ex) {} + final OrderedBidiMap bidiMap = getMap(); + Exception exception = assertThrows(NoSuchElementException.class, () -> { + bidiMap.firstKey(); + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("Map is empty")); + } resetFull(); - bidi = getMap(); + OrderedBidiMap bidi = getMap(); final K confirmedFirst = confirmed.keySet().iterator().next(); assertEquals(confirmedFirst, bidi.firstKey()); } public void testLastKey() { resetEmpty(); - OrderedBidiMap bidi = getMap(); - try { - bidi.lastKey(); - fail(); - } catch (final NoSuchElementException ex) {} + final OrderedBidiMap bidiMap = getMap(); + Exception exception = assertThrows(NoSuchElementException.class, () -> { + bidiMap.lastKey(); + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("Map is empty")); + } resetFull(); - bidi = getMap(); + OrderedBidiMap bidi = getMap(); K confirmedLast = null; for (final Iterator it = confirmed.keySet().iterator(); it.hasNext();) { confirmedLast = it.next(); @@ -81,10 +93,10 @@ public void testNextKey() { assertEquals(null, bidi.nextKey(getOtherKeys()[0])); if (!isAllowNullKey()) { try { - assertEquals(null, bidi.nextKey(null)); // this is allowed too + assertNull(bidi.nextKey(null)); // this is allowed too } catch (final NullPointerException ex) {} } else { - assertEquals(null, bidi.nextKey(null)); + assertNull(bidi.nextKey(null)); } resetFull(); @@ -96,15 +108,20 @@ public void testNextKey() { assertEquals(confirmedObject, bidi.nextKey(confirmedLast)); confirmedLast = confirmedObject; } - assertEquals(null, bidi.nextKey(confirmedLast)); + assertNull(bidi.nextKey(confirmedLast)); + final OrderedBidiMap bidiMap = (OrderedBidiMap) map; if (!isAllowNullKey()) { - try { - bidi.nextKey(null); - fail(); - } catch (final NullPointerException ex) {} + Exception exception = assertThrows(NullPointerException.class, () -> { + bidiMap.nextKey(null); + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("key")); + } } else { - assertEquals(null, bidi.nextKey(null)); + assertNull(bidiMap.nextKey(null)); } } @@ -114,10 +131,10 @@ public void testPreviousKey() { assertEquals(null, bidi.previousKey(getOtherKeys()[0])); if (!isAllowNullKey()) { try { - assertEquals(null, bidi.previousKey(null)); // this is allowed too + assertNull(bidi.previousKey(null)); // this is allowed too } catch (final NullPointerException ex) {} } else { - assertEquals(null, bidi.previousKey(null)); + assertNull(bidi.previousKey(null)); } resetFull(); @@ -131,15 +148,20 @@ public void testPreviousKey() { assertEquals(confirmedObject, bidi.previousKey(confirmedLast)); confirmedLast = confirmedObject; } - assertEquals(null, bidi.previousKey(confirmedLast)); + assertNull(bidi.previousKey(confirmedLast)); + final OrderedBidiMap bidiMap = getMap(); if (!isAllowNullKey()) { - try { - bidi.previousKey(null); - fail(); - } catch (final NullPointerException ex) {} + Exception exception = assertThrows(NullPointerException.class, () -> { + bidiMap.previousKey(null); + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("key")); + } } else { - assertEquals(null, bidi.previousKey(null)); + assertNull(bidiMap.previousKey(null)); } } diff --git a/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableBidiMapTest.java b/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableBidiMapTest.java index 770f6d9b4a..109d73e589 100644 --- a/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableBidiMapTest.java +++ b/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableBidiMapTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.bidimap; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; @@ -90,10 +93,10 @@ public void testDecorateFactory() { final BidiMap map = makeFullMap(); assertSame(map, UnmodifiableBidiMap.unmodifiableBidiMap(map)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableBidiMap.unmodifiableBidiMap(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("map")); } } diff --git a/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableOrderedBidiMapTest.java b/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableOrderedBidiMapTest.java index 92a2f3d7d0..a45cb501f7 100644 --- a/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableOrderedBidiMapTest.java +++ b/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableOrderedBidiMapTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.bidimap; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Map; import java.util.TreeMap; @@ -100,9 +103,9 @@ public void testDecorateFactory() { final OrderedBidiMap map = makeFullMap(); assertSame(map, UnmodifiableOrderedBidiMap.unmodifiableOrderedBidiMap(map)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableOrderedBidiMap.unmodifiableOrderedBidiMap(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("map")); } } diff --git a/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableSortedBidiMapTest.java b/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableSortedBidiMapTest.java index bb30ce99d3..48dc46a454 100644 --- a/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableSortedBidiMapTest.java +++ b/src/test/java/org/apache/commons/collections4/bidimap/UnmodifiableSortedBidiMapTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.bidimap; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.SortedMap; import java.util.TreeMap; @@ -106,10 +109,10 @@ public void testDecorateFactory() { final SortedBidiMap map = makeFullMap(); assertSame(map, UnmodifiableSortedBidiMap.unmodifiableSortedBidiMap(map)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableSortedBidiMap.unmodifiableSortedBidiMap(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("map")); } } diff --git a/src/test/java/org/apache/commons/collections4/collection/AbstractCollectionTest.java b/src/test/java/org/apache/commons/collections4/collection/AbstractCollectionTest.java index 2ef8725608..0919271306 100644 --- a/src/test/java/org/apache/commons/collections4/collection/AbstractCollectionTest.java +++ b/src/test/java/org/apache/commons/collections4/collection/AbstractCollectionTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.collection; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; @@ -508,7 +513,7 @@ public void testCollectionAdd() { final boolean r = getCollection().add(element); getConfirmed().add(element); verify(); - assertTrue("Empty collection changed after add", r); + assertTrue(r); assertEquals("Collection size is 1 after first add", 1, getCollection().size()); } @@ -522,7 +527,7 @@ public void testCollectionAdd() { size++; } assertEquals("Collection size should grow after add", size, getCollection().size()); - assertTrue("Collection should contain added element", getCollection().contains(element)); + assertTrue(getCollection().contains(element)); } } @@ -539,9 +544,9 @@ public void testCollectionAddAll() { boolean r = getCollection().addAll(Arrays.asList(elements)); getConfirmed().addAll(Arrays.asList(elements)); verify(); - assertTrue("Empty collection should change after addAll", r); + assertTrue(r); for (final E element : elements) { - assertTrue("Collection should contain added element", getCollection().contains(element)); + assertTrue(getCollection().contains(element)); } resetFull(); @@ -552,8 +557,7 @@ public void testCollectionAddAll() { verify(); assertTrue("Full collection should change after addAll", r); for (final E element : elements) { - assertTrue("Full collection should contain added element", - getCollection().contains(element)); + assertTrue(getCollection().contains(element)); } assertEquals("Size should increase after addAll", size + elements.length, getCollection().size()); @@ -563,7 +567,7 @@ public void testCollectionAddAll() { getConfirmed().addAll(Arrays.asList(getFullElements())); verify(); if (r) { - assertTrue("Size should increase if addAll returns true", size < getCollection().size()); + assertTrue(size < getCollection().size()); } else { assertEquals("Size should not change if addAll returns false", size, getCollection().size()); } @@ -579,42 +583,50 @@ public void testUnsupportedAdd() { } resetEmpty(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().add(getFullNonNullElements()[0]); - fail("Empty collection should not support add."); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertNotNull(exception.getMessage()); } // make sure things didn't change even if the expected exception was // thrown. verify(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().addAll(Arrays.asList(getFullElements())); - fail("Empty collection should not support addAll."); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertNotNull(exception.getMessage()); } // make sure things didn't change even if the expected exception was // thrown. verify(); resetFull(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().add(getFullNonNullElements()[0]); - fail("Full collection should not support add."); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertNotNull(exception.getMessage()); } // make sure things didn't change even if the expected exception was // thrown. verify(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().addAll(Arrays.asList(getOtherElements())); - fail("Full collection should not support addAll."); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertNotNull(exception.getMessage()); } // make sure things didn't change even if the expected exception was // thrown. @@ -663,8 +675,7 @@ public void testCollectionContains() { resetFull(); elements = getFullElements(); for (int i = 0; i < elements.length; i++) { - assertTrue("Full collection should contain element[" + i + "]", - getCollection().contains(elements[i])); + assertTrue(getCollection().contains(elements[i])); } // make sure calls to "contains" don't change anything verify(); @@ -682,8 +693,7 @@ public void testCollectionContains() { public void testCollectionContainsAll() { resetEmpty(); Collection col = new HashSet<>(); - assertTrue("Every Collection should contain all elements of an " + - "empty Collection.", getCollection().containsAll(col)); + assertTrue(getCollection().containsAll(col)); col.addAll(Arrays.asList(getOtherElements())); assertFalse("Empty Collection shouldn't contain all elements of " + "a non-empty Collection.", getCollection().containsAll(col)); @@ -695,8 +705,7 @@ public void testCollectionContainsAll() { col.clear(); col.addAll(Arrays.asList(getFullElements())); - assertTrue("Full collection should containAll full elements", - getCollection().containsAll(col)); + assertTrue(getCollection().containsAll(col)); // make sure calls to "containsAll" don't change anything verify(); @@ -704,17 +713,15 @@ public void testCollectionContainsAll() { final int max = getFullElements().length == 1 ? 1 : getFullElements().length <= 5 ? getFullElements().length - 1 : 5; col = Arrays.asList(getFullElements()).subList(min, max); - assertTrue("Full collection should containAll partial full elements", - getCollection().containsAll(col)); - assertTrue("Full collection should containAll itself", getCollection().containsAll(getCollection())); + assertTrue(getCollection().containsAll(col)); + assertTrue(getCollection().containsAll(getCollection())); // make sure calls to "containsAll" don't change anything verify(); col = new ArrayList<>(); col.addAll(Arrays.asList(getFullElements())); col.addAll(Arrays.asList(getFullElements())); - assertTrue("Full collection should containAll duplicate full elements", - getCollection().containsAll(col)); + assertTrue(getCollection().containsAll(col)); // make sure calls to "containsAll" don't change anything verify(); @@ -725,7 +732,7 @@ public void testCollectionContainsAll() { */ public void testCollectionIsEmpty() { resetEmpty(); - assertTrue("New Collection should be empty.", getCollection().isEmpty()); + assertTrue(getCollection().isEmpty()); // make sure calls to "isEmpty() don't change anything verify(); @@ -740,39 +747,41 @@ public void testCollectionIsEmpty() { */ public void testCollectionIterator() { resetEmpty(); - Iterator it1 = getCollection().iterator(); - assertFalse("Iterator for empty Collection shouldn't have next.", it1.hasNext()); - try { - it1.next(); - fail("Iterator at end of Collection should throw " - + "NoSuchElementException when next is called."); - } catch (final NoSuchElementException e) { - // expected + final Iterator it = getCollection().iterator(); + assertFalse("Iterator for empty Collection shouldn't have next.", it.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { + it.next(); + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("element")); } // make sure nothing has changed after non-modification verify(); resetFull(); - it1 = getCollection().iterator(); + Iterator it1 = getCollection().iterator(); for (int i = 0; i < getCollection().size(); i++) { - assertTrue("Iterator for full collection should haveNext", it1.hasNext()); + assertTrue(it1.hasNext()); it1.next(); } assertFalse("Iterator should be finished", it1.hasNext()); final ArrayList list = new ArrayList<>(); - it1 = getCollection().iterator(); + final Iterator it2 = getCollection().iterator(); for (int i = 0; i < getCollection().size(); i++) { - final E next = it1.next(); - assertTrue("Collection should contain element returned by its iterator", - getCollection().contains(next)); + final E next = it2.next(); + assertTrue(getCollection().contains(next)); list.add(next); } - try { - it1.next(); - fail("iterator.next() should raise NoSuchElementException after it finishes"); - } catch (final NoSuchElementException e) { - // expected + exception = assertThrows(NoSuchElementException.class, () -> { + it2.next(); + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertNotNull(exception.getMessage()); } // make sure nothing has changed after non-modification verify(); @@ -788,21 +797,25 @@ public void testCollectionIteratorRemove() { } resetEmpty(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { getCollection().iterator().remove(); - fail("New iterator.remove should raise IllegalState"); - } catch (final IllegalStateException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("Iterator")); } verify(); - try { - final Iterator iter = getCollection().iterator(); - iter.hasNext(); - iter.remove(); - fail("New iterator.remove should raise IllegalState even after hasNext"); - } catch (final IllegalStateException e) { - // expected + final Iterator iter1 = getCollection().iterator(); + iter1.hasNext(); + exception = assertThrows(IllegalStateException.class, () -> { + iter1.remove(); + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("Iterator")); } verify(); @@ -835,17 +848,19 @@ public void testCollectionIteratorRemove() { assertEquals("Collection should shrink by one after iterator.remove", size, getCollection().size()); } - assertTrue("Collection should be empty after iterator purge", getCollection().isEmpty()); + assertTrue(getCollection().isEmpty()); resetFull(); - iter = getCollection().iterator(); - iter.next(); - iter.remove(); - try { - iter.remove(); - fail("Second iter.remove should raise IllegalState"); - } catch (final IllegalStateException e) { - // expected + final Iterator iter2 = getCollection().iterator(); + iter2.next(); + iter2.remove(); + exception = assertThrows(IllegalStateException.class, () -> { + iter2.remove(); + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertNotNull(exception.getMessage()); } } @@ -860,7 +875,7 @@ public void testCollectionRemove() { resetEmpty(); final E[] elements = getFullElements(); for (final E element : elements) { - assertTrue("Shouldn't remove nonexistent element", !getCollection().remove(element)); + assertTrue(!getCollection().remove(element)); verify(); } @@ -875,8 +890,7 @@ public void testCollectionRemove() { final int size = getCollection().size(); for (final E element : elements) { resetFull(); - assertTrue("Collection should remove extant element: " + element, - getCollection().remove(element)); + assertTrue(getCollection().remove(element)); // if the elements aren't distinguishable, we can just remove a // matching element from the confirmed collection and verify @@ -904,12 +918,10 @@ public void testCollectionRemoveAll() { } resetEmpty(); - assertTrue("Empty collection removeAll should return false for empty input", - !getCollection().removeAll(Collections.EMPTY_SET)); + assertTrue(!getCollection().removeAll(Collections.EMPTY_SET)); verify(); - assertTrue("Empty collection removeAll should return false for nonempty input", - !getCollection().removeAll(new ArrayList<>(getCollection()))); + assertTrue(!getCollection().removeAll(new ArrayList<>(getCollection()))); verify(); resetFull(); @@ -919,8 +931,7 @@ public void testCollectionRemoveAll() { assertFalse("Full collection removeAll should return false for other elements", getCollection().removeAll(Arrays.asList(getOtherElements()))); verify(); - assertTrue("Full collection removeAll should return true for full elements", - getCollection().removeAll(new HashSet<>(getCollection()))); + assertTrue(getCollection().removeAll(new HashSet<>(getCollection()))); getConfirmed().removeAll(new HashSet<>(getConfirmed())); verify(); @@ -930,11 +941,11 @@ public void testCollectionRemoveAll() { final int max = getFullElements().length == 1 ? 1 : getFullElements().length <= 5 ? getFullElements().length - 1 : 5; final Collection all = Arrays.asList(getFullElements()).subList(min, max); - assertTrue("Full collection removeAll should work", getCollection().removeAll(all)); + assertTrue(getCollection().removeAll(all)); getConfirmed().removeAll(all); verify(); - assertTrue("Collection should shrink after removeAll", getCollection().size() < size); + assertTrue(getCollection().size() < size); for (final E element : all) { assertFalse("Collection shouldn't contain removed element", getCollection().contains(element)); } @@ -960,8 +971,7 @@ public void testCollectionRemoveIf() { assertFalse("Full collection removeIf should return false for a predicate that returns only false", getCollection().removeIf(e -> false)); verify(); - assertTrue("Full collection removeIf should return true for a predicate that returns only true", - getCollection().removeIf(e -> true)); + assertTrue(getCollection().removeIf(e -> true)); getConfirmed().removeIf(e -> true); verify(); @@ -976,7 +986,7 @@ public void testCollectionRemoveIf() { final Predicate filter = e -> target.equals(e); - assertTrue("Full collection removeIf should work", getCollection().removeIf(filter)); + assertTrue(getCollection().removeIf(filter)); getConfirmed().removeIf(filter); verify(); @@ -1003,13 +1013,12 @@ public void testCollectionRetainAll() { verify(); resetFull(); - assertTrue("Collection should change from retainAll empty", - getCollection().retainAll(Collections.EMPTY_SET)); + assertTrue(getCollection().retainAll(Collections.EMPTY_SET)); getConfirmed().retainAll(Collections.EMPTY_SET); verify(); resetFull(); - assertTrue("Collection changed from retainAll other", getCollection().retainAll(other)); + assertTrue(getCollection().retainAll(other)); getConfirmed().retainAll(other); verify(); @@ -1024,13 +1033,12 @@ public void testCollectionRetainAll() { size = getCollection().size(); final int min = getFullElements().length < 4 ? 0 : 2; final int max = getFullElements().length <= 5 ? getFullElements().length - 1 : 5; - assertTrue("Collection should changed by partial retainAll", - getCollection().retainAll(elements.subList(min, max))); + assertTrue(getCollection().retainAll(elements.subList(min, max))); getConfirmed().retainAll(elements.subList(min, max)); verify(); for (final E element : getCollection()) { - assertTrue("Collection only contains retained element", elements.subList(min, max).contains(element)); + assertTrue(elements.subList(min, max).contains(element)); } } @@ -1052,7 +1060,7 @@ public void testCollectionSize() { assertEquals("Size of new Collection is 0.", 0, getCollection().size()); resetFull(); - assertTrue("Size of full collection should be greater than zero", getCollection().size() > 0); + assertTrue(getCollection().size() > 0); } /** @@ -1073,8 +1081,7 @@ public void testCollectionToArray() { final boolean[] matched = new boolean[array.length]; for (int i = 0; i < array.length; i++) { - assertTrue("Collection should contain element in toArray", - getCollection().contains(array[i])); + assertTrue(getCollection().contains(array[i])); boolean match = false; // find a match in the confirmed array @@ -1095,7 +1102,7 @@ public void testCollectionToArray() { } } for (final boolean element : matched) { - assertTrue("Collection should return all its elements in " + "toArray", element); + assertTrue(element); } } @@ -1107,25 +1114,24 @@ public void testCollectionToArray2() { Object[] a = new Object[] { new Object(), null, null }; Object[] array = getCollection().toArray(a); assertEquals("Given array shouldn't shrink", array, a); - assertNull("Last element should be set to null", a[0]); + assertNull(a[0]); verify(); resetFull(); - try { - array = getCollection().toArray(new Void[0]); - fail("toArray(new Void[0]) should raise ArrayStore"); - } catch (final ArrayStoreException e) { - // expected + Exception exception = assertThrows(ArrayStoreException.class, () -> { + getCollection().toArray(new Void[0]); + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertNotNull(exception.getMessage()); } verify(); - try { - // Casting to Object[] allows compilation on Java 11. - array = getCollection().toArray((Object[]) null); - fail("toArray(null) should raise NPE"); - } catch (final NullPointerException e) { - // expected - } + exception = assertThrows(NullPointerException.class, () -> { + getCollection().toArray((Object[]) null); + }); + assertNull(exception.getMessage()); verify(); array = getCollection().toArray(new Object[0]); @@ -1178,54 +1184,66 @@ public void testUnsupportedRemove() { } resetEmpty(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().clear(); - fail("clear should raise UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("List is fixed size")); } verify(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().remove(null); - fail("remove should raise UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("List is fixed size")); } verify(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().removeIf(e -> true); - fail("removeIf should raise UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("List is fixed size")); } verify(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().removeAll(null); - fail("removeAll should raise UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("List is fixed size")); } verify(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().retainAll(null); - fail("retainAll should raise UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("List is fixed size")); } verify(); resetFull(); - try { - final Iterator iterator = getCollection().iterator(); - iterator.next(); + final Iterator iterator = getCollection().iterator(); + iterator.next(); + exception = assertThrows(UnsupportedOperationException.class, () -> { iterator.remove(); - fail("iterator.remove should raise UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("remove() is not supported")); } verify(); @@ -1241,28 +1259,24 @@ public void testCollectionIteratorFailFast() { if (isAddSupported()) { resetFull(); - try { - final Iterator iter = getCollection().iterator(); - final E o = getOtherElements()[0]; - getCollection().add(o); - getConfirmed().add(o); + final Iterator iter = getCollection().iterator(); + final E o = getOtherElements()[0]; + getCollection().add(o); + getConfirmed().add(o); + Exception exception = assertThrows(ConcurrentModificationException.class, () -> { iter.next(); - fail("next after add should raise ConcurrentModification"); - } catch (final ConcurrentModificationException e) { - // expected - } + }); + assertNull(exception.getMessage()); verify(); resetFull(); - try { - final Iterator iter = getCollection().iterator(); - getCollection().addAll(Arrays.asList(getOtherElements())); - getConfirmed().addAll(Arrays.asList(getOtherElements())); - iter.next(); - fail("next after addAll should raise ConcurrentModification"); - } catch (final ConcurrentModificationException e) { - // expected - } + final Iterator iter1 = getCollection().iterator(); + getCollection().addAll(Arrays.asList(getOtherElements())); + getConfirmed().addAll(Arrays.asList(getOtherElements())); + exception = assertThrows(ConcurrentModificationException.class, () -> { + iter1.next(); + }); + assertNull(exception.getMessage()); verify(); } @@ -1271,58 +1285,45 @@ public void testCollectionIteratorFailFast() { } resetFull(); - try { - final Iterator iter = getCollection().iterator(); - getCollection().clear(); + final Iterator iter = getCollection().iterator(); + getCollection().clear(); + Exception exception = assertThrows(ConcurrentModificationException.class, () -> { iter.next(); - fail("next after clear should raise ConcurrentModification"); - } catch (final ConcurrentModificationException e) { - // expected - } catch (final NoSuchElementException e) { - // (also legal given spec) - } + }); + assertNull(exception.getMessage()); resetFull(); - try { - final Iterator iter = getCollection().iterator(); - getCollection().remove(getFullElements()[0]); - iter.next(); - fail("next after remove should raise ConcurrentModification"); - } catch (final ConcurrentModificationException e) { - // expected - } + final Iterator iter1 = getCollection().iterator(); + getCollection().remove(getFullElements()[0]); + exception = assertThrows(ConcurrentModificationException.class, () -> { + iter1.next(); + }); + assertNull(exception.getMessage()); resetFull(); - try { - final Iterator iter = getCollection().iterator(); - getCollection().removeIf(e -> false); - iter.next(); - fail("next after removeIf should raise ConcurrentModification"); - } catch (final ConcurrentModificationException e) { - // expected - } + final Iterator iter2 = getCollection().iterator(); + getCollection().removeIf(e -> false); + exception = assertThrows(ConcurrentModificationException.class, () -> { + iter2.next(); + }); + assertNull(exception.getMessage()); resetFull(); - try { - final Iterator iter = getCollection().iterator(); - final List sublist = Arrays.asList(getFullElements()).subList(2, 5); - getCollection().removeAll(sublist); - iter.next(); - fail("next after removeAll should raise ConcurrentModification"); - } catch (final ConcurrentModificationException e) { - // expected - } + final Iterator iter3 = getCollection().iterator(); + final List sublist = Arrays.asList(getFullElements()).subList(2, 5); + getCollection().removeAll(sublist); + exception = assertThrows(ConcurrentModificationException.class, () -> { + iter3.next(); + }); + assertNull(exception.getMessage()); resetFull(); - try { - final Iterator iter = getCollection().iterator(); - final List sublist = Arrays.asList(getFullElements()).subList(2, 5); - getCollection().retainAll(sublist); - iter.next(); - fail("next after retainAll should raise ConcurrentModification"); - } catch (final ConcurrentModificationException e) { - // expected - } + final Iterator iter4 = getCollection().iterator(); + getCollection().retainAll(sublist); + exception = assertThrows(ConcurrentModificationException.class, () -> { + iter4.next(); + }); + assertNull(exception.getMessage()); } @Override diff --git a/src/test/java/org/apache/commons/collections4/collection/CompositeCollectionTest.java b/src/test/java/org/apache/commons/collections4/collection/CompositeCollectionTest.java index a0e8a06e8c..fb76bb0ed6 100644 --- a/src/test/java/org/apache/commons/collections4/collection/CompositeCollectionTest.java +++ b/src/test/java/org/apache/commons/collections4/collection/CompositeCollectionTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.collection; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -24,8 +29,6 @@ import java.util.List; import java.util.function.Predicate; -import org.junit.Assert; - /** * Extension of {@link AbstractCollectionTest} for exercising the * {@link CompositeCollection} implementation. @@ -253,21 +256,21 @@ public void testAddNullList() { final ArrayList nullList = null; final CompositeCollection cc = new CompositeCollection<>(); cc.addComposited(nullList); - Assert.assertEquals(0, cc.size()); + assertEquals(0, cc.size()); } public void testAddNullLists2Args() { final ArrayList nullList = null; final CompositeCollection cc = new CompositeCollection<>(); cc.addComposited(nullList, nullList); - Assert.assertEquals(0, cc.size()); + assertEquals(0, cc.size()); } public void testAddNullListsVarArgs() { final ArrayList nullList = null; final CompositeCollection cc = new CompositeCollection<>(); cc.addComposited(nullList, nullList, nullList); - Assert.assertEquals(0, cc.size()); + assertEquals(0, cc.size()); } @SuppressWarnings("unchecked") @@ -426,12 +429,10 @@ public void testToCollection() { @Override public void testUnsupportedRemove() { resetFull(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().remove(null); - fail("remove should raise UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported on CompositeCollection without a CollectionMutator strategy")); verify(); } diff --git a/src/test/java/org/apache/commons/collections4/collection/IndexedCollectionTest.java b/src/test/java/org/apache/commons/collections4/collection/IndexedCollectionTest.java index be8704b6d6..bd9f44fbdb 100644 --- a/src/test/java/org/apache/commons/collections4/collection/IndexedCollectionTest.java +++ b/src/test/java/org/apache/commons/collections4/collection/IndexedCollectionTest.java @@ -17,6 +17,8 @@ package org.apache.commons.collections4.collection; import static java.util.Arrays.asList; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.Serializable; import java.util.ArrayList; @@ -129,12 +131,10 @@ public void testEnsureDuplicateObjectsCauseException() throws Exception { final Collection coll = makeUniqueTestCollection(); coll.add("1"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { coll.add("1"); - fail(); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Duplicate key in uniquely indexed collection")); } public void testDecoratedCollectionIsIndexedOnCreation() throws Exception { diff --git a/src/test/java/org/apache/commons/collections4/collection/PredicatedCollectionTest.java b/src/test/java/org/apache/commons/collections4/collection/PredicatedCollectionTest.java index 1fdf575de7..f48458a221 100644 --- a/src/test/java/org/apache/commons/collections4/collection/PredicatedCollectionTest.java +++ b/src/test/java/org/apache/commons/collections4/collection/PredicatedCollectionTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.collection; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -83,12 +86,10 @@ public Collection makeTestCollection() { public void testIllegalAdd() { final Collection c = makeTestCollection(); final Integer i = 3; - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { c.add((E) i); - fail("Integer should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3' ")); assertFalse("Collection shouldn't contain illegal element", c.contains(i)); } @@ -100,12 +101,10 @@ public void testIllegalAddAll() { elements.add((E) "two"); elements.add((E) Integer.valueOf(3)); elements.add((E) "four"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { c.addAll(elements); - fail("Integer should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3' ")); assertFalse("Collection shouldn't contain illegal element", c.contains("one")); assertFalse("Collection shouldn't contain illegal element", c.contains("two")); assertFalse("Collection shouldn't contain illegal element", c.contains(3)); diff --git a/src/test/java/org/apache/commons/collections4/collection/UnmodifiableBoundedCollectionTest.java b/src/test/java/org/apache/commons/collections4/collection/UnmodifiableBoundedCollectionTest.java index 11cb110efc..517a07125e 100644 --- a/src/test/java/org/apache/commons/collections4/collection/UnmodifiableBoundedCollectionTest.java +++ b/src/test/java/org/apache/commons/collections4/collection/UnmodifiableBoundedCollectionTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.collection; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -92,10 +95,10 @@ public void testDecorateFactory() { final BoundedCollection coll = makeFullCollection(); assertSame(coll, UnmodifiableBoundedCollection.unmodifiableBoundedCollection(coll)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableBoundedCollection.unmodifiableBoundedCollection(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("collection")); } } diff --git a/src/test/java/org/apache/commons/collections4/collection/UnmodifiableCollectionTest.java b/src/test/java/org/apache/commons/collections4/collection/UnmodifiableCollectionTest.java index d8c86009b7..ab7742d8aa 100644 --- a/src/test/java/org/apache/commons/collections4/collection/UnmodifiableCollectionTest.java +++ b/src/test/java/org/apache/commons/collections4/collection/UnmodifiableCollectionTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.collection; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -81,10 +84,10 @@ public void testDecorateFactory() { final Collection coll = makeFullCollection(); assertSame(coll, UnmodifiableCollection.unmodifiableCollection(coll)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableCollection.unmodifiableCollection(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("collection")); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/comparators/BooleanComparatorTest.java b/src/test/java/org/apache/commons/collections4/comparators/BooleanComparatorTest.java index 41067b9f8e..1d4acdbec6 100644 --- a/src/test/java/org/apache/commons/collections4/comparators/BooleanComparatorTest.java +++ b/src/test/java/org/apache/commons/collections4/comparators/BooleanComparatorTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.comparators; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -130,35 +133,25 @@ protected void orderIndependentTests(final BooleanComparator comp) { protected void nullArgumentTests(final BooleanComparator comp) { assertNotNull(comp); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { comp.compare(null, null); - fail("Expected NullPointerException"); - } catch (final NullPointerException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(NullPointerException.class, () -> { comp.compare(Boolean.TRUE, null); - fail("Expected NullPointerException"); - } catch (final NullPointerException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(NullPointerException.class, () -> { comp.compare(Boolean.FALSE, null); - fail("Expected NullPointerException"); - } catch (final NullPointerException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(NullPointerException.class, () -> { comp.compare(null, Boolean.TRUE); - fail("Expected NullPointerException"); - } catch (final NullPointerException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(NullPointerException.class, () -> { comp.compare(null, Boolean.FALSE); - fail("Expected NullPointerException"); - } catch (final NullPointerException e) { - // expected - } + }); + assertNull(exception.getMessage()); } } diff --git a/src/test/java/org/apache/commons/collections4/comparators/ComparatorChainTest.java b/src/test/java/org/apache/commons/collections4/comparators/ComparatorChainTest.java index 9ddc8da47a..be9fa7a41a 100644 --- a/src/test/java/org/apache/commons/collections4/comparators/ComparatorChainTest.java +++ b/src/test/java/org/apache/commons/collections4/comparators/ComparatorChainTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.comparators; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.Serializable; import java.util.Arrays; import java.util.Comparator; @@ -67,11 +70,10 @@ public void testBadNoopComparatorChain() { final ComparatorChain chain = new ComparatorChain<>(); final Integer i1 = 4; final Integer i2 = 6; - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { chain.compare(i1, i2); - fail("An exception should be thrown when a chain contains zero comparators."); - } catch (final UnsupportedOperationException e) { - } + }); + assertTrue(exception.getMessage().contains("ComparatorChains must contain at least one Comparator")); } @Test @@ -92,11 +94,10 @@ public void testBadListComparatorChain() { final ComparatorChain chain = new ComparatorChain<>(list); final Integer i1 = 4; final Integer i2 = 6; - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { chain.compare(i1, i2); - fail("An exception should be thrown when a chain contains zero comparators."); - } catch (final UnsupportedOperationException e) { - } + }); + assertTrue(exception.getMessage().contains("ComparatorChains must contain at least one Comparator")); } @Test diff --git a/src/test/java/org/apache/commons/collections4/comparators/FixedOrderComparatorTest.java b/src/test/java/org/apache/commons/collections4/comparators/FixedOrderComparatorTest.java index 97ace6065f..93499f7ecc 100644 --- a/src/test/java/org/apache/commons/collections4/comparators/FixedOrderComparatorTest.java +++ b/src/test/java/org/apache/commons/collections4/comparators/FixedOrderComparatorTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.comparators; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; @@ -143,39 +146,33 @@ public void testLock() { assertFalse(comparator.isLocked()); comparator.compare("New York", "Tokyo"); assertTrue(comparator.isLocked()); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { comparator.add("Minneapolis"); - fail("Should have thrown an UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // success -- ignore - } + }); + assertTrue(exception.getMessage().contains("Cannot modify a FixedOrderComparator after a comparison")); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { comparator.addAsEqual("New York", "Minneapolis"); - fail("Should have thrown an UnsupportedOperationException"); - } catch (final UnsupportedOperationException e) { - // success -- ignore - } + }); + assertTrue(exception.getMessage().contains("Cannot modify a FixedOrderComparator after a comparison")); } @Test public void testUnknownObjectBehavior() { - FixedOrderComparator comparator = new FixedOrderComparator<>(topCities); - try { - comparator.compare("New York", "Minneapolis"); - fail("Should have thrown a IllegalArgumentException"); - } catch (final IllegalArgumentException e) { - // success-- ignore - } - try { - comparator.compare("Minneapolis", "New York"); - fail("Should have thrown a IllegalArgumentException"); - } catch (final IllegalArgumentException e) { - // success-- ignore - } - assertEquals(FixedOrderComparator.UnknownObjectBehavior.EXCEPTION, comparator.getUnknownObjectBehavior()); + final FixedOrderComparator fixedOrderComparator = new FixedOrderComparator<>(topCities); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + fixedOrderComparator.compare("New York", "Minneapolis"); + }); + assertTrue(exception.getMessage().contains("Attempting to compare unknown object Minneapolis")); - comparator = new FixedOrderComparator<>(topCities); + exception = assertThrows(IllegalArgumentException.class, () -> { + fixedOrderComparator.compare("Minneapolis", "New York"); + }); + assertTrue(exception.getMessage().contains("Attempting to compare unknown object Minneapolis")); + + assertEquals(FixedOrderComparator.UnknownObjectBehavior.EXCEPTION, fixedOrderComparator.getUnknownObjectBehavior()); + + FixedOrderComparator comparator = new FixedOrderComparator<>(topCities); comparator.setUnknownObjectBehavior(FixedOrderComparator.UnknownObjectBehavior.BEFORE); assertEquals(FixedOrderComparator.UnknownObjectBehavior.BEFORE, comparator.getUnknownObjectBehavior()); LinkedList keys = new LinkedList<>(Arrays.asList(topCities)); diff --git a/src/test/java/org/apache/commons/collections4/iterators/AbstractIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/AbstractIteratorTest.java index 9389de040c..b7d85ef2ff 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/AbstractIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/AbstractIteratorTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Iterator; import java.util.NoSuchElementException; @@ -107,13 +112,14 @@ public void testEmptyIterator() { final Iterator it = makeEmptyIterator(); // hasNext() should return false - assertEquals("hasNext() should return false for empty iterators", false, it.hasNext()); + assertFalse(it.hasNext()); // next() should throw a NoSuchElementException - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail("NoSuchElementException must be thrown when Iterator is exhausted"); - } catch (final NoSuchElementException e) { + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } verify(); @@ -131,14 +137,10 @@ public void testFullIterator() { final Iterator it = makeObject(); // hasNext() must be true (ensure makeFullIterator is correct!) - assertEquals("hasNext() should return true for at least one element", true, it.hasNext()); + assertTrue(it.hasNext()); // next() must not throw exception (ensure makeFullIterator is correct!) - try { - it.next(); - } catch (final NoSuchElementException e) { - fail("Full iterators must have at least one element"); - } + it.next(); // iterate through while (it.hasNext()) { @@ -147,10 +149,11 @@ public void testFullIterator() { } // next() must throw NoSuchElementException now - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail("NoSuchElementException must be thrown when Iterator is exhausted"); - } catch (final NoSuchElementException e) { + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } assertNotNull(it.toString()); @@ -164,17 +167,22 @@ public void testRemove() { if (!supportsRemove()) { // check for UnsupportedOperationException if not supported - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { it.remove(); - } catch (final UnsupportedOperationException ex) {} + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); + } return; } // should throw IllegalStateException before next() called - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); + } verify(); // remove after next should be fine @@ -182,10 +190,12 @@ public void testRemove() { it.remove(); // should throw IllegalStateException for second remove() - try { + exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); + } } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/AbstractListIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/AbstractListIteratorTest.java index 04a5596cf6..3bbae29f23 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/AbstractListIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/AbstractListIteratorTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.ListIterator; import java.util.NoSuchElementException; @@ -97,23 +103,25 @@ public void testEmptyListIteratorIsIndeedEmpty() { final ListIterator it = makeEmptyIterator(); - assertEquals(false, it.hasNext()); + assertFalse(it.hasNext()); assertEquals(0, it.nextIndex()); - assertEquals(false, it.hasPrevious()); + assertFalse(it.hasPrevious()); assertEquals(-1, it.previousIndex()); // next() should throw a NoSuchElementException - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail("NoSuchElementException must be thrown from empty ListIterator"); - } catch (final NoSuchElementException e) { + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } // previous() should throw a NoSuchElementException - try { + exception = assertThrows(NoSuchElementException.class, () -> { it.previous(); - fail("NoSuchElementException must be thrown from empty ListIterator"); - } catch (final NoSuchElementException e) { + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } @@ -128,12 +136,13 @@ public void testWalkForwardAndBack() { } // check state at end - assertEquals(false, it.hasNext()); - assertEquals(true, it.hasPrevious()); - try { + assertFalse(it.hasNext()); + assertTrue(it.hasPrevious()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail("NoSuchElementException must be thrown from next at end of ListIterator"); - } catch (final NoSuchElementException e) { + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("element")); } // loop back through comparing @@ -146,12 +155,13 @@ public void testWalkForwardAndBack() { } // check state at start - assertEquals(true, it.hasNext()); - assertEquals(false, it.hasPrevious()); - try { + assertTrue(it.hasNext()); + assertFalse(it.hasPrevious()); + exception = assertThrows(NoSuchElementException.class, () -> { it.previous(); - fail("NoSuchElementException must be thrown from previous at start of ListIterator"); - } catch (final NoSuchElementException e) { + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } @@ -159,20 +169,22 @@ public void testWalkForwardAndBack() { * Test add behavior. */ public void testAdd() { - ListIterator it = makeObject(); + final ListIterator it1 = makeObject(); final E addValue = addSetValue(); if (!supportsAdd()) { // check for UnsupportedOperationException if not supported - try { - it.add(addValue); - fail("UnsupportedOperationException must be thrown from add of " + it.getClass().getSimpleName()); - } catch (final UnsupportedOperationException ex) {} + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + it1.add(addValue); + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("not support")); + } return; } // add at start should be OK, added should be previous - it = makeObject(); + ListIterator it = makeObject(); it.add(addValue); assertEquals(addValue, it.previous()); @@ -200,18 +212,22 @@ public void testSet() { if (!supportsSet()) { // check for UnsupportedOperationException if not supported - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { it.set(addSetValue()); - fail("UnsupportedOperationException must be thrown from set in " + it.getClass().getSimpleName()); - } catch (final UnsupportedOperationException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("not support")); + } return; } // should throw IllegalStateException before next() called - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.set(addSetValue()); - fail(); - } catch (final IllegalStateException ex) {} + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); + } // set after next should be fine it.next(); @@ -227,11 +243,10 @@ public void testRemoveThenSet() { if (supportsRemove() && supportsSet()) { it.next(); it.remove(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.set(addSetValue()); - fail("IllegalStateException must be thrown from set after remove"); - } catch (final IllegalStateException e) { - } + }); + assertNull(exception.getMessage()); } } @@ -241,10 +256,11 @@ public void testAddThenSet() { if (supportsAdd() && supportsSet()) { it.next(); it.add(addSetValue()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.set(addSetValue()); - fail("IllegalStateException must be thrown from set after add"); - } catch (final IllegalStateException e) { + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } } @@ -259,10 +275,11 @@ public void testAddThenRemove() { if (supportsAdd() && supportsRemove()) { it.next(); it.add(addSetValue()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail("IllegalStateException must be thrown from remove after add"); - } catch (final IllegalStateException e) { + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/AbstractMapIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/AbstractMapIteratorTest.java index 775801c289..6d31f82fce 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/AbstractMapIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/AbstractMapIteratorTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; @@ -116,39 +122,47 @@ public void testEmptyMapIterator() { } final MapIterator it = makeEmptyIterator(); - assertEquals(false, it.hasNext()); + assertFalse(it.hasNext()); // next() should throw a NoSuchElementException - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) {} - + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + } // getKey() should throw an IllegalStateException - try { + exception = assertThrows(IllegalStateException.class, () -> { it.getKey(); - fail(); - } catch (final IllegalStateException ex) {} + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); + } // getValue() should throw an IllegalStateException - try { + exception = assertThrows(IllegalStateException.class, () -> { it.getValue(); - fail(); - } catch (final IllegalStateException ex) {} + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); + } if (!supportsSetValue()) { // setValue() should throw an UnsupportedOperationException/IllegalStateException - try { + exception = assertThrows(Exception.class, () -> { it.setValue(addSetValues()[0]); - fail(); - } catch (final UnsupportedOperationException ex) { - } catch (final IllegalStateException ex) {} + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); + } } else { // setValue() should throw an IllegalStateException - try { + exception = assertThrows(IllegalStateException.class, () -> { it.setValue(addSetValues()[0]); - fail(); - } catch (final IllegalStateException ex) {} + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); + } } } @@ -163,23 +177,23 @@ public void testFullMapIterator() { final MapIterator it = makeObject(); final Map map = getMap(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); final Set set = new HashSet<>(); while (it.hasNext()) { // getKey final K key = it.next(); assertSame("it.next() should equals getKey()", key, it.getKey()); - assertTrue("Key must be in map", map.containsKey(key)); - assertTrue("Key must be unique", set.add(key)); + assertTrue(map.containsKey(key)); + assertTrue(set.add(key)); // getValue final V value = it.getValue(); if (!isGetStructuralModify()) { assertSame("Value must be mapped to key", map.get(key), value); } - assertTrue("Value must be in map", map.containsValue(value)); + assertTrue(map.containsValue(value)); verify(); } @@ -196,15 +210,17 @@ public void testMapIteratorSet() { final MapIterator it = makeObject(); final Map map = getMap(); final Map confirmed = getConfirmedMap(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); final K key = it.next(); final V value = it.getValue(); if (!supportsSetValue()) { - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { it.setValue(newValue); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("not support")); + } return; } final V old = it.setValue(newValue); @@ -212,11 +228,10 @@ public void testMapIteratorSet() { assertSame("Key must not change after setValue", key, it.getKey()); assertSame("Value must be changed after setValue", newValue, it.getValue()); assertSame("setValue must return old value", value, old); - assertEquals("Map must contain key", true, map.containsKey(key)); + assertTrue(map.containsKey(key)); // test against confirmed, as map may contain value twice - assertEquals("Map must not contain old value", - confirmed.containsValue(old), map.containsValue(old)); - assertEquals("Map must contain new value", true, map.containsValue(newValue)); + assertEquals(confirmed.containsValue(old), map.containsValue(old)); + assertTrue(map.containsValue(newValue)); verify(); it.setValue(newValue); // same value - should be OK @@ -238,26 +253,29 @@ public void testRemove() { // override final MapIterator it = makeObject(); final Map map = getMap(); final Map confirmed = getConfirmedMap(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); final K key = it.next(); if (!supportsRemove()) { - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { it.remove(); - fail(); - } catch (final UnsupportedOperationException ex) { + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("not support")); } return; } it.remove(); confirmed.remove(key); - assertEquals(false, map.containsKey(key)); + assertFalse(map.containsKey(key)); verify(); - try { - it.remove(); // second remove fails - } catch (final IllegalStateException ex) { + Exception exception = assertThrows(IllegalStateException.class, () -> { + it.remove(); + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("can only be called")); } verify(); } @@ -271,7 +289,7 @@ public void testMapIteratorSetRemoveSet() { final MapIterator it = makeObject(); final Map confirmed = getConfirmedMap(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); final K key = it.next(); it.setValue(newValue); @@ -279,10 +297,12 @@ public void testMapIteratorSetRemoveSet() { confirmed.remove(key); verify(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.setValue(newValue); - fail(); - } catch (final IllegalStateException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("can only be called")); + } verify(); } @@ -294,17 +314,19 @@ public void testMapIteratorRemoveGetKey() { final MapIterator it = makeObject(); final Map confirmed = getConfirmedMap(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); final K key = it.next(); it.remove(); confirmed.remove(key); verify(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.getKey(); - fail(); - } catch (final IllegalStateException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("can only be called")); + } verify(); } @@ -316,17 +338,19 @@ public void testMapIteratorRemoveGetValue() { final MapIterator it = makeObject(); final Map confirmed = getConfirmedMap(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); final K key = it.next(); it.remove(); confirmed.remove(key); verify(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.getValue(); - fail(); - } catch (final IllegalStateException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("can only be called")); + } verify(); } diff --git a/src/test/java/org/apache/commons/collections4/iterators/AbstractOrderedMapIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/AbstractOrderedMapIteratorTest.java index b6c967737f..18cec702ac 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/AbstractOrderedMapIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/AbstractOrderedMapIteratorTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; @@ -67,11 +73,13 @@ public void testEmptyMapIterator() { super.testEmptyMapIterator(); final OrderedMapIterator it = makeEmptyIterator(); - assertEquals(false, it.hasPrevious()); - try { + assertFalse(it.hasPrevious()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.previous(); - fail(); - } catch (final NoSuchElementException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + } } //----------------------------------------------------------------------- @@ -89,24 +97,24 @@ public void testFullMapIterator() { final OrderedMapIterator it = makeObject(); final Map map = getMap(); - assertEquals(true, it.hasNext()); - assertEquals(false, it.hasPrevious()); + assertTrue(it.hasNext()); + assertFalse(it.hasPrevious()); final Set set = new HashSet<>(); while (it.hasNext()) { // getKey final K key = it.next(); assertSame("it.next() should equals getKey()", key, it.getKey()); - assertTrue("Key must be in map", map.containsKey(key)); - assertTrue("Key must be unique", set.add(key)); + assertTrue(map.containsKey(key)); + assertTrue(set.add(key)); // getValue final V value = it.getValue(); if (!isGetStructuralModify()) { assertSame("Value must be mapped to key", map.get(key), value); } - assertTrue("Value must be in map", map.containsValue(value)); + assertTrue(map.containsValue(value)); - assertEquals(true, it.hasPrevious()); + assertTrue(it.hasPrevious()); verify(); } @@ -114,17 +122,17 @@ public void testFullMapIterator() { // getKey final Object key = it.previous(); assertSame("it.previous() should equals getKey()", key, it.getKey()); - assertTrue("Key must be in map", map.containsKey(key)); - assertTrue("Key must be unique", set.remove(key)); + assertTrue(map.containsKey(key)); + assertTrue(set.remove(key)); // getValue final Object value = it.getValue(); if (!isGetStructuralModify()) { assertSame("Value must be mapped to key", map.get(key), value); } - assertTrue("Value must be in map", map.containsValue(value)); + assertTrue(map.containsValue(value)); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); verify(); } @@ -145,8 +153,8 @@ public void testMapIteratorOrder() { assertEquals("keySet() not consistent", new ArrayList<>(map.keySet()), new ArrayList<>(map.keySet())); final Iterator it2 = map.keySet().iterator(); - assertEquals(true, it.hasNext()); - assertEquals(true, it2.hasNext()); + assertTrue(it.hasNext()); + assertTrue(it2.hasNext()); final List list = new ArrayList<>(); while (it.hasNext()) { final K key = it.next(); diff --git a/src/test/java/org/apache/commons/collections4/iterators/ArrayIterator2Test.java b/src/test/java/org/apache/commons/collections4/iterators/ArrayIterator2Test.java index e7acf4947c..cc80c1c248 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/ArrayIterator2Test.java +++ b/src/test/java/org/apache/commons/collections4/iterators/ArrayIterator2Test.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Iterator; import java.util.NoSuchElementException; @@ -64,18 +69,15 @@ public void testIterator() { final Integer testValue = Integer.valueOf(element); final Number iterValue = (Number) iter.next(); - assertEquals("Iteration value is correct", testValue, iterValue); + assertEquals(testValue, iterValue); } - assertTrue("Iterator should now be empty", !iter.hasNext()); + assertTrue(!iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - } catch (final Exception e) { - assertTrue( - "NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); - } + }); + assertNull(exception.getMessage()); } public void testIndexedArray() { @@ -86,7 +88,7 @@ public void testIndexedArray() { iter.next(); } - assertEquals("the count should be right using ArrayIterator(Object,2) ", count, testArray.length - 2); + assertEquals(count, testArray.length - 2); iter = makeArrayIterator(testArray, 1, testArray.length - 1); count = 0; @@ -95,53 +97,34 @@ public void testIndexedArray() { iter.next(); } - assertEquals( - "the count should be right using ArrayIterator(Object,1," + (testArray.length - 1) + ") ", - count, - testArray.length - 2); + assertEquals(count, testArray.length - 2); - try { - iter = makeArrayIterator(testArray, -1); - fail("new ArrayIterator(Object,-1) should throw an ArrayIndexOutOfBoundsException"); - } catch (final ArrayIndexOutOfBoundsException aioobe) { - // expected - } + Exception exception = assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + makeArrayIterator(testArray, -1); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that starts before the start of the array.")); - try { - iter = makeArrayIterator(testArray, testArray.length + 1); - fail("new ArrayIterator(Object,length+1) should throw an ArrayIndexOutOfBoundsException"); - } catch (final ArrayIndexOutOfBoundsException aioobe) { - // expected - } + exception = assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + makeArrayIterator(testArray, testArray.length + 1); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that starts beyond the end of the array")); - try { - iter = makeArrayIterator(testArray, 0, -1); - fail("new ArrayIterator(Object,0,-1) should throw an ArrayIndexOutOfBoundsException"); - } catch (final ArrayIndexOutOfBoundsException aioobe) { - // expected - } - try { - iter = makeArrayIterator(testArray, 0, testArray.length + 1); - fail("new ArrayIterator(Object,0,length+1) should throw an ArrayIndexOutOfBoundsException"); - } catch (final ArrayIndexOutOfBoundsException aioobe) { - // expected - } + exception = assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + makeArrayIterator(testArray, 0, -1); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that ends before the start of the array.")); - try { - iter = makeArrayIterator(testArray, 1, 1); - // expected not to fail - } catch (final IllegalArgumentException iae) { - // MODIFIED: an iterator over a zero-length section of array - // should be perfectly legal behavior - fail("new ArrayIterator(Object,1,1) should NOT throw an IllegalArgumentException"); - } + exception = assertThrows(ArrayIndexOutOfBoundsException.class, () -> { + makeArrayIterator(testArray, 0, testArray.length + 1); + }); + assertTrue(exception.getMessage().contains("Attempt to make an ArrayIterator that")); - try { - iter = makeArrayIterator(testArray, testArray.length - 1, testArray.length - 2); - fail("new ArrayIterator(Object,length-2,length-1) should throw an IllegalArgumentException"); - } catch (final IllegalArgumentException iae) { - // expected - } + makeArrayIterator(testArray, 1, 1); + + exception = assertThrows(IllegalArgumentException.class, () -> { + makeArrayIterator(testArray, testArray.length - 1, testArray.length - 2); + }); + assertTrue(exception.getMessage().contains("End index must not be less than start index.")); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/ArrayIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/ArrayIteratorTest.java index 74d51f18df..2d0829b19a 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/ArrayIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/ArrayIteratorTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Iterator; import java.util.NoSuchElementException; @@ -56,24 +61,19 @@ public void testIterator() { assertEquals("Iteration value is correct", testValue, iterValue); } - assertTrue("Iterator should now be empty", !iter.hasNext()); + assertTrue(!iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - } catch (final Exception e) { - assertTrue( - "NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); - } + }); + assertNull(exception.getMessage()); } public void testNullArray() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { new ArrayIterator<>(null); - fail("Constructor should throw a NullPointerException when constructed with a null array"); - } catch (final NullPointerException e) { - // expected - } + }); + assertNull(exception.getMessage()); } public void testReset() { diff --git a/src/test/java/org/apache/commons/collections4/iterators/ArrayListIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/ArrayListIteratorTest.java index 0cf8bf32cf..788bf32df4 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/ArrayListIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/ArrayListIteratorTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import java.util.ListIterator; import java.util.NoSuchElementException; @@ -68,18 +73,15 @@ public void testListIterator() { final Object testValue = testArray[x]; final Object iterValue = iter.previous(); - assertEquals("Iteration value is correct", testValue, iterValue); + assertEquals(testValue, iterValue); } - assertTrue("Iterator should now be empty", !iter.hasPrevious()); + assertTrue(!iter.hasPrevious()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.previous(); - } catch (final Exception e) { - assertTrue( - "NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); - } + }); + assertNull(exception.getMessage()); } @@ -101,20 +103,15 @@ public void testListIteratorSet() { x++; } - assertTrue("The two arrays should have the same value, i.e. {0,1,2}", Arrays.equals(testData, result)); + assertTrue(Arrays.equals(testData, result)); // a call to set() before a call to next() or previous() should throw an IllegalStateException - iter = makeArrayListIterator(testArray); - - try { - iter.set((E) "should fail"); - fail("ListIterator#set should fail if next() or previous() have not yet been called."); - } catch (final IllegalStateException e) { - // expected - } catch (final Throwable t) { // should never happen - fail(t.toString()); - } + final ListIterator iter1 = makeArrayListIterator(testArray); + Exception exception = assertThrows(IllegalStateException.class, () -> { + iter1.set((E) "should fail"); + }); + assertTrue(exception.getMessage().contains("must call next() or previous() before a call to set()")); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/BoundedIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/BoundedIteratorTest.java index eeb548580c..cd05c735bb 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/BoundedIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/BoundedIteratorTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -81,11 +87,10 @@ public void testBounded() { assertEquals("f", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -114,11 +119,10 @@ public void testSameAsDecorated() { assertEquals("g", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -130,11 +134,10 @@ public void testSameAsDecorated() { public void testEmptyBounded() { final Iterator iter = new BoundedIterator<>(testList.iterator(), 3, 0); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -143,11 +146,10 @@ public void testEmptyBounded() { */ @Test public void testNegativeOffset() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new BoundedIterator<>(testList.iterator(), -1, 4); - fail("Expected IllegalArgumentException."); - } catch (final IllegalArgumentException iae) { /* Success case */ - } + }); + assertTrue(exception.getMessage().contains("Offset parameter must not be negative")); } /** @@ -156,11 +158,10 @@ public void testNegativeOffset() { */ @Test public void testNegativeMax() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new BoundedIterator<>(testList.iterator(), 3, -1); - fail("Expected IllegalArgumentException."); - } catch (final IllegalArgumentException iae) { /* Success case */ - } + }); + assertTrue(exception.getMessage().contains("Max parameter must not be negative.")); } /** @@ -172,11 +173,10 @@ public void testNegativeMax() { public void testOffsetGreaterThanSize() { final Iterator iter = new BoundedIterator<>(testList.iterator(), 10, 4); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -203,11 +203,10 @@ public void testMaxGreaterThanSize() { assertEquals("g", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -219,11 +218,10 @@ public void testRemoveWithoutCallingNext() { final List testListCopy = new ArrayList<>(testList); final Iterator iter = new BoundedIterator<>(testListCopy.iterator(), 1, 5); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("Expected IllegalStateException."); - } catch (final IllegalStateException ise) { /* Success case */ - } + }); + assertTrue(exception.getMessage().contains("remove() can not be called before calling next()")); } /** @@ -239,11 +237,10 @@ public void testRemoveCalledTwice() { assertEquals("b", iter.next()); iter.remove(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("Expected IllegalStateException."); - } catch (final IllegalStateException ise) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -271,11 +268,10 @@ public void testRemoveFirst() { assertEquals("f", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -303,11 +299,10 @@ public void testRemoveMiddle() { assertEquals("f", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -331,21 +326,19 @@ public void testRemoveLast() { assertEquals("f", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); iter.remove(); assertFalse(testListCopy.contains("f")); assertFalse(iter.hasNext()); - try { + exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -364,10 +357,9 @@ public void remove() { final Iterator iter = new BoundedIterator<>(mockIterator, 1, 5); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { iter.remove(); - fail("Expected UnsupportedOperationException."); - } catch (final UnsupportedOperationException usoe) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/FilterIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/FilterIteratorTest.java index 461f9f2453..02ad1d1b7b 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/FilterIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/FilterIteratorTest.java @@ -17,6 +17,11 @@ package org.apache.commons.collections4.iterators; import static org.apache.commons.collections4.functors.TruePredicate.truePredicate; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; @@ -121,11 +126,11 @@ public void testSetIterator() { final FilterIterator filterIterator = new FilterIterator<>(iter1); filterIterator.setPredicate(truePredicate()); // this iterator has elements - assertEquals(true, filterIterator.hasNext()); + assertTrue(filterIterator.hasNext()); // this iterator has no elements filterIterator.setIterator(iter2); - assertEquals(false, filterIterator.hasNext()); + assertFalse(filterIterator.hasNext()); } /** @@ -147,12 +152,10 @@ public void testSetPredicate() { private void verifyNoMoreElements() { assertTrue(!iterator.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iterator.next(); - fail("NoSuchElementException expected"); - } catch (final NoSuchElementException e) { - // success - } + }); + assertNull(exception.getMessage()); } private void verifyElementsInPredicate(final String[] elements) { @@ -179,7 +182,7 @@ private void verifyElementsInPredicate(final String[] elements) { if (iterator.hasNext()) { final Object last = iterator.next(); iterator.remove(); - assertTrue("Base of FilterIterator still contains removed element.", !list.contains(last)); + assertTrue(!list.contains(last)); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/IteratorChainTest.java b/src/test/java/org/apache/commons/collections4/iterators/IteratorChainTest.java index e3d8e325d5..fc4e315eb5 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/IteratorChainTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/IteratorChainTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -76,17 +81,15 @@ public void testIterator() { for (final String testValue : testArray) { final Object iterValue = iter.next(); - assertEquals( "Iteration value is correct", testValue, iterValue ); + assertEquals("Iteration value is correct", testValue, iterValue); } - assertTrue("Iterator should now be empty", !iter.hasNext()); + assertTrue(!iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - } catch (final Exception e) { - assertTrue("NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); - } + }); + assertNull(exception.getMessage()); } public void testRemoveFromFilteredIterator() { @@ -117,12 +120,10 @@ public void testRemoveFromFilteredIterator() { public void testRemove() { final Iterator iter = makeObject(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("Calling remove before the first call to next() should throw an exception"); - } catch (final IllegalStateException e) { - - } + }); + assertNull(exception.getMessage()); for (final String testValue : testArray) { final String iterValue = iter.next(); @@ -134,9 +135,9 @@ public void testRemove() { } } - assertTrue("List is empty", list1.size() == 0); - assertTrue("List is empty", list2.size() == 1); - assertTrue("List is empty", list3.size() == 0); + assertTrue(list1.size() == 0); + assertTrue(list2.size() == 1); + assertTrue(list3.size() == 0); } public void testFirstIteratorIsEmptyBug() { @@ -148,26 +149,26 @@ public void testFirstIteratorIsEmptyBug() { final IteratorChain chain = new IteratorChain<>(); chain.addIterator(empty.iterator()); chain.addIterator(notEmpty.iterator()); - assertTrue("should have next", chain.hasNext()); + assertTrue(chain.hasNext()); assertEquals("A", chain.next()); - assertTrue("should have next", chain.hasNext()); + assertTrue(chain.hasNext()); assertEquals("B", chain.next()); - assertTrue("should have next", chain.hasNext()); + assertTrue(chain.hasNext()); assertEquals("C", chain.next()); - assertTrue("should not have next", !chain.hasNext()); + assertTrue(!chain.hasNext()); } public void testEmptyChain() { final IteratorChain chain = new IteratorChain<>(); assertEquals(false, chain.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { chain.next(); - fail(); - } catch (final NoSuchElementException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { chain.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/IteratorEnumerationTest.java b/src/test/java/org/apache/commons/collections4/iterators/IteratorEnumerationTest.java index 2c6c4f0f96..8b45d9abe2 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/IteratorEnumerationTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/IteratorEnumerationTest.java @@ -16,12 +16,17 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import org.junit.Test; -import static org.junit.Assert.*; /** * Tests the IteratorEnumeration. @@ -42,11 +47,9 @@ public void testEnumeration() { assertEquals("c", enumeration.nextElement()); assertFalse(enumeration.hasMoreElements()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { enumeration.nextElement(); - fail("NoSuchElementException expected"); - } catch (final NoSuchElementException e) { - // expected - } + }); + assertNull(exception.getMessage()); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/LazyIteratorChainTest.java b/src/test/java/org/apache/commons/collections4/iterators/LazyIteratorChainTest.java index 3827c41692..856c25f583 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/LazyIteratorChainTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/LazyIteratorChainTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -93,14 +98,12 @@ public void testIterator() { assertEquals( "Iteration value is correct", testValue, iterValue ); } - assertTrue("Iterator should now be empty", !iter.hasNext()); + assertTrue(!iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - } catch (final Exception e) { - assertTrue("NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); - } + }); + assertNull(exception.getMessage()); } public void testRemoveFromFilteredIterator() { @@ -131,12 +134,10 @@ public void testRemoveFromFilteredIterator() { public void testRemove() { final Iterator iter = makeObject(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("Calling remove before the first call to next() should throw an exception"); - } catch (final IllegalStateException e) { - - } + }); + assertNull(exception.getMessage()); for (final String testValue : testArray) { final String iterValue = iter.next(); @@ -148,9 +149,9 @@ public void testRemove() { } } - assertTrue("List is empty", list1.size() == 0); - assertTrue("List is empty", list2.size() == 1); - assertTrue("List is empty", list3.size() == 0); + assertTrue(list1.size() == 0); + assertTrue(list2.size() == 1); + assertTrue(list3.size() == 0); } public void testFirstIteratorIsEmptyBug() { @@ -171,25 +172,25 @@ protected Iterator nextIterator(final int count) { return null; } }; - assertTrue("should have next", chain.hasNext()); + assertTrue(chain.hasNext()); assertEquals("A", chain.next()); - assertTrue("should have next", chain.hasNext()); + assertTrue(chain.hasNext()); assertEquals("B", chain.next()); - assertTrue("should have next", chain.hasNext()); + assertTrue(chain.hasNext()); assertEquals("C", chain.next()); - assertTrue("should not have next", !chain.hasNext()); + assertTrue(!chain.hasNext()); } public void testEmptyChain() { final LazyIteratorChain chain = makeEmptyIterator(); assertEquals(false, chain.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { chain.next(); - fail(); - } catch (final NoSuchElementException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); + exception = assertThrows(IllegalStateException.class, () -> { chain.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertTrue(exception.getMessage().contains("Iterator contains no elements")); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWrapper2Test.java b/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWrapper2Test.java index b5cfbd2789..5a771e750b 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWrapper2Test.java +++ b/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWrapper2Test.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.List; import java.util.ListIterator; @@ -70,14 +76,12 @@ public void testIterator() { assertEquals("Iteration value is correct", testValue, iterValue); } - assertTrue("Iterator should now be empty", !iter.hasNext()); + assertTrue(!iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - } catch (final Exception e) { - assertTrue("NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); - } + }); + assertNull(exception.getMessage()); // now, read it backwards for (int i = testArray.length - 1; i > -1; --i) { @@ -87,12 +91,10 @@ public void testIterator() { assertEquals( "Iteration value is correct", testValue, iterValue ); } - try { + exception = assertThrows(NoSuchElementException.class, () -> { iter.previous(); - } catch (final Exception e) { - assertTrue("NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); - } + }); + assertNull(exception.getMessage()); // now, read it forwards again for (final String testValue : testArray) { @@ -111,11 +113,10 @@ public void testRemove() { assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("ListIteratorWrapper#remove() should fail; must be initially positioned first"); - } catch (final IllegalStateException e) { - } + }); + assertNull(exception.getMessage()); //no change from invalid op: assertEquals(-1, iter.previousIndex()); @@ -136,11 +137,10 @@ public void testRemove() { assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); - try { + exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("ListIteratorWrapper#remove() should fail; must be repositioned first"); - } catch (final IllegalStateException e) { - } + }); + assertNull(exception.getMessage()); //no change from invalid op: assertEquals(-1, iter.previousIndex()); diff --git a/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWrapperTest.java b/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWrapperTest.java index a1a19603a4..807ab08e1f 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWrapperTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/ListIteratorWrapperTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.List; import java.util.ListIterator; @@ -68,16 +74,16 @@ public void testIterator() { for (final String testValue : testArray) { final Object iterValue = iter.next(); - assertEquals("Iteration value is correct", testValue, iterValue); + assertEquals(testValue, iterValue); } - assertTrue("Iterator should now be empty", !iter.hasNext()); + assertTrue(!iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - } catch (final Exception e) { - assertTrue("NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } // now, read it backwards @@ -85,21 +91,21 @@ public void testIterator() { final Object testValue = testArray[i]; final E iterValue = iter.previous(); - assertEquals( "Iteration value is correct", testValue, iterValue ); + assertEquals(testValue, iterValue ); } - try { + exception = assertThrows(NoSuchElementException.class, () -> { iter.previous(); - } catch (final Exception e) { - assertTrue("NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } // now, read it forwards again for (final String testValue : testArray) { final Object iterValue = iter.next(); - assertEquals("Iteration value is correct", testValue, iterValue); + assertEquals(testValue, iterValue); } } @@ -112,11 +118,10 @@ public void testRemove() { assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("ListIteratorWrapper#remove() should fail; must be initially positioned first"); - } catch (final IllegalStateException e) { - } + }); + assertNotNull(exception.getMessage()); //no change from invalid op: assertEquals(-1, iter.previousIndex()); @@ -137,11 +142,10 @@ public void testRemove() { assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); - try { + exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("ListIteratorWrapper#remove() should fail; must be repositioned first"); - } catch (final IllegalStateException e) { - } + }); + assertNotNull(exception.getMessage()); //no change from invalid op: assertEquals(-1, iter.previousIndex()); @@ -172,10 +176,11 @@ public void testRemove() { assertEquals(-1, iter.previousIndex()); assertEquals(0, iter.nextIndex()); - try { + exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("ListIteratorWrapper does not support the remove() method while dug into the cache via previous()"); - } catch (final IllegalStateException e) { + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } //no change from invalid op: @@ -214,15 +219,15 @@ public void testReset() { assertFalse("No previous elements after reset()", iter.hasPrevious()); // after reset, the results should be the same as before - assertEquals("First element should be the same", first, iter.next()); - assertEquals("Second elment should be the same", second, iter.next()); + assertEquals(first, iter.next()); + assertEquals(second, iter.next()); // after passing the point, where we resetted, continuation should work as expected for (int i = 2; i < testArray.length; i++) { final Object testValue = testArray[i]; final E iterValue = iter.next(); - assertEquals("Iteration value is correct", testValue, iterValue); + assertEquals(testValue, iterValue); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/LoopingIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/LoopingIteratorTest.java index 7d9b7600f9..facfec8d3c 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/LoopingIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/LoopingIteratorTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -23,8 +28,6 @@ import org.junit.Test; -import static org.junit.Assert.*; - /** * Tests the LoopingIterator class. * @@ -36,11 +39,10 @@ public class LoopingIteratorTest { */ @Test public void testConstructorEx() throws Exception { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { new LoopingIterator<>(null); - fail(); - } catch (final NullPointerException ex) { - } + }); + assertTrue(exception.getMessage().contains("collection")); } /** @@ -51,13 +53,12 @@ public void testConstructorEx() throws Exception { public void testLooping0() throws Exception { final List list = new ArrayList<>(); final LoopingIterator loop = new LoopingIterator<>(list); - assertTrue("hasNext should return false", !loop.hasNext()); + assertTrue(!loop.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { loop.next(); - fail("NoSuchElementException was not thrown during next() call."); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("There are no elements for this iterator to loop on")); } /** @@ -69,13 +70,13 @@ public void testLooping1() throws Exception { final List list = Arrays.asList("a"); final LoopingIterator loop = new LoopingIterator<>(list); - assertTrue("1st hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("a", loop.next()); - assertTrue("2nd hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("a", loop.next()); - assertTrue("3rd hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("a", loop.next()); } @@ -89,13 +90,13 @@ public void testLooping2() throws Exception { final List list = Arrays.asList("a", "b"); final LoopingIterator loop = new LoopingIterator<>(list); - assertTrue("1st hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("a", loop.next()); - assertTrue("2nd hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("b", loop.next()); - assertTrue("3rd hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("a", loop.next()); } @@ -109,16 +110,16 @@ public void testLooping3() throws Exception { final List list = Arrays.asList("a", "b", "c"); final LoopingIterator loop = new LoopingIterator<>(list); - assertTrue("1st hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("a", loop.next()); - assertTrue("2nd hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("b", loop.next()); - assertTrue("3rd hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("c", loop.next()); - assertTrue("4th hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("a", loop.next()); } @@ -131,29 +132,28 @@ public void testLooping3() throws Exception { public void testRemoving1() throws Exception { final List list = new ArrayList<>(Arrays.asList("a", "b", "c")); final LoopingIterator loop = new LoopingIterator<>(list); - assertEquals("list should have 3 elements.", 3, list.size()); + assertEquals(3, list.size()); - assertTrue("1st hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("a", loop.next()); loop.remove(); // removes a - assertEquals("list should have 2 elements.", 2, list.size()); + assertEquals(2, list.size()); - assertTrue("2nd hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("b", loop.next()); loop.remove(); // removes b - assertEquals("list should have 1 elements.", 1, list.size()); + assertEquals(1, list.size()); - assertTrue("3rd hasNext should return true", loop.hasNext()); + assertTrue(loop.hasNext()); assertEquals("c", loop.next()); loop.remove(); // removes c - assertEquals("list should have 0 elements.", 0, list.size()); + assertEquals(0, list.size()); - assertFalse("4th hasNext should return false", loop.hasNext()); - try { + assertFalse(loop.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { loop.next(); - fail("Expected NoSuchElementException to be thrown."); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("There are no elements for this iterator to loop on")); } /** diff --git a/src/test/java/org/apache/commons/collections4/iterators/LoopingListIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/LoopingListIteratorTest.java index a3bf48bd6a..af4c03c993 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/LoopingListIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/LoopingListIteratorTest.java @@ -16,13 +16,17 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test; -import static org.junit.Assert.*; /** * Tests the LoopingListIterator class. @@ -35,11 +39,10 @@ public class LoopingListIteratorTest { */ @Test public void testConstructorEx() throws Exception { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { new LoopingListIterator<>(null); - fail(); - } catch (final NullPointerException ex) { - } + }); + assertTrue(exception.getMessage().contains("collection")); } /** @@ -52,17 +55,15 @@ public void testLooping0() throws Exception { assertFalse(loop.hasNext()); assertFalse(loop.hasPrevious()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { loop.next(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("There are no elements for this iterator to loop on")); - try { + exception = assertThrows(NoSuchElementException.class, () -> { loop.previous(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("There are no elements for this iterator to loop on")); } /** @@ -189,11 +190,10 @@ public void testRemovingElementsAndIteratingForward() { assertEquals(0, list.size()); assertFalse(loop.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { loop.next(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("There are no elements for this iterator to loop on")); } /** @@ -220,11 +220,10 @@ public void testRemovingElementsAndIteratingBackwards() { assertEquals(0, list.size()); assertFalse(loop.hasPrevious()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { loop.previous(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("There are no elements for this iterator to loop on")); } /** diff --git a/src/test/java/org/apache/commons/collections4/iterators/NodeListIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/NodeListIteratorTest.java index bde677637e..482288eeae 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/NodeListIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/NodeListIteratorTest.java @@ -17,6 +17,8 @@ package org.apache.commons.collections4.iterators; import static org.easymock.EasyMock.*; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Iterator; @@ -112,12 +114,10 @@ public boolean supportsRemove() { //----------------------------------------------------------------------- public void testNullConstructor(){ - try{ + Exception exception = assertThrows(NullPointerException.class, () -> { new NodeListIterator((Node) null); - fail("NullPointerException expected!"); - }catch(final NullPointerException e){ - // expected. - } + }); + assertTrue(exception.getMessage().contains("node")); } /** diff --git a/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayIteratorTest.java index f17d3d1ca1..8c9d95443b 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayIteratorTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Iterator; import java.util.NoSuchElementException; @@ -73,25 +78,19 @@ public void testIterator() { assertEquals("Iteration value is correct", testValue, iterValue); } - assertTrue("Iterator should now be empty", !iter.hasNext()); + assertTrue(!iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - } catch (final Exception e) { - assertTrue( - "NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); - } + }); + assertNull(exception.getMessage()); } public void testNullArray() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { makeArrayIterator(null); - - fail("Constructor should throw a NullPointerException when constructed with a null array"); - } catch (final NullPointerException e) { - // expected - } + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") diff --git a/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayListIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayListIteratorTest.java index 7d9975d5f5..b8a87ab6cc 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayListIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/ObjectArrayListIteratorTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import java.util.ListIterator; import java.util.NoSuchElementException; @@ -68,16 +73,12 @@ public void testListIterator() { assertEquals("Iteration value is correct", testValue, iterValue); } - assertTrue("Iterator should now be empty", !iter.hasPrevious()); + assertTrue(!iter.hasPrevious()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.previous(); - } catch (final Exception e) { - assertTrue( - "NoSuchElementException must be thrown", - e.getClass().equals(new NoSuchElementException().getClass())); - } - + }); + assertNull(exception.getMessage()); } /** @@ -98,20 +99,15 @@ public void testListIteratorSet() { x++; } - assertTrue("The two arrays should have the same value, i.e. {0,1,2}", Arrays.equals(testData, result)); + assertTrue(Arrays.equals(testData, result)); // a call to set() before a call to next() or previous() should throw an IllegalStateException - iter = makeArrayListIterator((E[]) testArray); - - try { - iter.set((E) "should fail"); - fail("ListIterator#set should fail if next() or previous() have not yet been called."); - } catch (final IllegalStateException e) { - // expected - } catch (final Throwable t) { // should never happen - fail(t.toString()); - } + final ListIterator iter1 = makeArrayListIterator((E[]) testArray); + Exception exception = assertThrows(IllegalStateException.class, () -> { + iter1.set((E) "should fail"); + }); + assertTrue(exception.getMessage().contains("must call next() or previous() before a call to set()")); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/ObjectGraphIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/ObjectGraphIteratorTest.java index caff4ed312..85a7d5f606 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/ObjectGraphIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/ObjectGraphIteratorTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -74,35 +80,31 @@ public ObjectGraphIterator makeObject() { public void testIteratorConstructor_null1() { final Iterator it = new ObjectGraphIterator<>(null); - assertEquals(false, it.hasNext()); - try { + assertFalse(it.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); + exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail(); - } catch (final IllegalStateException ex) { - } + }); + assertTrue(exception.getMessage().contains("Iterator remove() cannot be called at this time")); } public void testIteratorConstructor_null_next() { final Iterator it = new ObjectGraphIterator<>(null); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); } public void testIteratorConstructor_null_remove() { final Iterator it = new ObjectGraphIterator<>(null); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail(); - } catch (final IllegalStateException ex) { - } + }); + assertTrue(exception.getMessage().contains("Iterator remove() cannot be called at this time")); } //----------------------------------------------------------------------- @@ -110,17 +112,15 @@ public void testIteratorConstructorIteration_Empty() { final List> iteratorList = new ArrayList<>(); final Iterator it = new ObjectGraphIterator<>(iteratorList.iterator()); - assertEquals(false, it.hasNext()); - try { + assertFalse(it.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); + exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail(); - } catch (final IllegalStateException ex) { - } + }); + assertTrue(exception.getMessage().contains("Iterator remove() cannot be called at this time")); } public void testIteratorConstructorIteration_Simple() { @@ -131,15 +131,14 @@ public void testIteratorConstructorIteration_Simple() { final Iterator it = new ObjectGraphIterator<>(iteratorList.iterator()); for (int i = 0; i < 6; i++) { - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals(testArray[i], it.next()); } - assertEquals(false, it.hasNext()); - try { + assertFalse(it.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); } public void testIteratorConstructorIteration_SimpleNoHasNext() { @@ -152,11 +151,10 @@ public void testIteratorConstructorIteration_SimpleNoHasNext() { for (int i = 0; i < 6; i++) { assertEquals(testArray[i], it.next()); } - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); } public void testIteratorConstructorIteration_WithEmptyIterators() { @@ -171,15 +169,14 @@ public void testIteratorConstructorIteration_WithEmptyIterators() { final Iterator it = new ObjectGraphIterator<>(iteratorList.iterator()); for (int i = 0; i < 6; i++) { - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals(testArray[i], it.next()); } - assertEquals(false, it.hasNext()); - try { + assertFalse(it.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); } public void testIteratorConstructorRemove() { @@ -193,7 +190,7 @@ public void testIteratorConstructorRemove() { assertEquals(testArray[i], it.next()); it.remove(); } - assertEquals(false, it.hasNext()); + assertFalse(it.hasNext()); assertEquals(0, list1.size()); assertEquals(0, list2.size()); assertEquals(0, list3.size()); @@ -208,10 +205,10 @@ public void testIteration_IteratorOfIterators() { final Iterator it = new ObjectGraphIterator<>(iteratorList.iterator(), null); for (int i = 0; i < 6; i++) { - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals(testArray[i], it.next()); } - assertEquals(false, it.hasNext()); + assertFalse(it.hasNext()); } public void testIteration_IteratorOfIteratorsWithEmptyIterators() { @@ -226,41 +223,38 @@ public void testIteration_IteratorOfIteratorsWithEmptyIterators() { final Iterator it = new ObjectGraphIterator<>(iteratorList.iterator(), null); for (int i = 0; i < 6; i++) { - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals(testArray[i], it.next()); } - assertEquals(false, it.hasNext()); + assertFalse(it.hasNext()); } //----------------------------------------------------------------------- public void testIteration_RootNull() { final Iterator it = new ObjectGraphIterator<>(null, null); - assertEquals(false, it.hasNext()); - try { + assertFalse(it.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); + exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail(); - } catch (final IllegalStateException ex) { - } + }); + assertTrue(exception.getMessage().contains("Iterator remove() cannot be called at this time")); } public void testIteration_RootNoTransformer() { final Forest forest = new Forest(); final Iterator it = new ObjectGraphIterator<>(forest, null); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(forest, it.next()); - assertEquals(false, it.hasNext()); - try { + assertFalse(it.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); } public void testIteration_Transformed1() { @@ -268,14 +262,13 @@ public void testIteration_Transformed1() { final Leaf l1 = forest.addTree().addBranch().addLeaf(); final Iterator it = new ObjectGraphIterator<>(forest, new LeafFinder()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l1, it.next()); - assertEquals(false, it.hasNext()); - try { + assertFalse(it.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); } public void testIteration_Transformed2() { @@ -296,22 +289,21 @@ public void testIteration_Transformed2() { final Iterator it = new ObjectGraphIterator<>(forest, new LeafFinder()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l1, it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l2, it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l3, it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l4, it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l5, it.next()); - assertEquals(false, it.hasNext()); - try { + assertFalse(it.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); } public void testIteration_Transformed3() { @@ -332,22 +324,21 @@ public void testIteration_Transformed3() { final Iterator it = new ObjectGraphIterator<>(forest, new LeafFinder()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l1, it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l2, it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l3, it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l4, it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertSame(l5, it.next()); - assertEquals(false, it.hasNext()); - try { + assertFalse(it.hasNext()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException ex) { - } + }); + assertTrue(exception.getMessage().contains("No more elements in the iteration")); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/iterators/PeekingIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/PeekingIteratorTest.java index cdf10f5aa3..3bba363a59 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/PeekingIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/PeekingIteratorTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -106,12 +112,10 @@ public void testIteratorExhausted() { assertFalse(it.hasNext()); assertNull(it.peek()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.element(); - fail(); - } catch (final NoSuchElementException e) { - // expected - } + }); + assertNull(exception.getMessage()); } @Test @@ -123,12 +127,10 @@ public void testIllegalRemove() { assertTrue(it.hasNext()); assertEquals("b", it.peek()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail(); - } catch (final IllegalStateException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("peek() or element() called before remove()")); } private void validate(final Iterator iter, final E... items) { diff --git a/src/test/java/org/apache/commons/collections4/iterators/PermutationIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/PermutationIteratorTest.java index 2f38a095e6..953033fedd 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/PermutationIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/PermutationIteratorTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; @@ -72,7 +78,7 @@ public PermutationIterator makeObject() { @SuppressWarnings("boxing") // OK in test code public void testPermutationResultSize() { int factorial = 1; - for (int i = 0; i < 8; i++, factorial*=i) { + for (int i = 0; i < 8; i++, factorial *= i) { final List list = new ArrayList<>(); for (int j = 0; j < i; j++) { list.add(j); @@ -164,12 +170,10 @@ public void testPermutationException() { resultsList.add(permutation); } //asking for another permutation should throw an exception - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail(); - } catch (final NoSuchElementException e) { - // expected - } + }); + assertNull(exception.getMessage()); } public void testPermutatorHasMore() { diff --git a/src/test/java/org/apache/commons/collections4/iterators/ReverseListIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/ReverseListIteratorTest.java index ba6516f2e1..0be9e704f4 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/ReverseListIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/ReverseListIteratorTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -54,24 +60,22 @@ public ReverseListIterator makeObject() { public void testEmptyListIteratorIsIndeedEmpty() { final ListIterator it = makeEmptyIterator(); - assertEquals(false, it.hasNext()); + assertFalse(it.hasNext()); assertEquals(-1, it.nextIndex()); // reversed index - assertEquals(false, it.hasPrevious()); + assertFalse(it.hasPrevious()); assertEquals(0, it.previousIndex()); // reversed index // next() should throw a NoSuchElementException - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail("NoSuchElementException must be thrown from empty ListIterator"); - } catch (final NoSuchElementException e) { - } + }); + assertNull(exception.getMessage()); // previous() should throw a NoSuchElementException - try { + exception = assertThrows(NoSuchElementException.class, () -> { it.previous(); - fail("NoSuchElementException must be thrown from empty ListIterator"); - } catch (final NoSuchElementException e) { - } + }); + assertNull(exception.getMessage()); } @Override @@ -83,8 +87,8 @@ public void testWalkForwardAndBack() { } // check state at end - assertEquals(false, it.hasNext()); - assertEquals(true, it.hasPrevious()); + assertFalse(it.hasNext()); + assertTrue(it.hasPrevious()); // this had to be commented out, as there is a bug in the JDK before JDK1.5 // where calling previous at the start of an iterator would push the cursor @@ -105,41 +109,40 @@ public void testWalkForwardAndBack() { } // check state at start - assertEquals(true, it.hasNext()); - assertEquals(false, it.hasPrevious()); - try { + assertTrue(it.hasNext()); + assertFalse(it.hasPrevious()); + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.previous(); - fail("NoSuchElementException must be thrown from previous at start of ListIterator"); - } catch (final NoSuchElementException e) { - } + }); + assertNull(exception.getMessage()); } //----------------------------------------------------------------------- public void testReverse() { final ListIterator it = makeObject(); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals(3, it.nextIndex()); - assertEquals(false, it.hasPrevious()); + assertFalse(it.hasPrevious()); assertEquals(4, it.previousIndex()); assertEquals("Four", it.next()); assertEquals(2, it.nextIndex()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals(3, it.previousIndex()); - assertEquals(true, it.hasPrevious()); + assertTrue(it.hasPrevious()); assertEquals("Three", it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals(1, it.nextIndex()); - assertEquals(true, it.hasPrevious()); + assertTrue(it.hasPrevious()); assertEquals(2, it.previousIndex()); assertEquals("Two", it.next()); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); assertEquals(0, it.nextIndex()); - assertEquals(true, it.hasPrevious()); + assertTrue(it.hasPrevious()); assertEquals(1, it.previousIndex()); assertEquals("One", it.next()); - assertEquals(false, it.hasNext()); + assertFalse(it.hasNext()); assertEquals(-1, it.nextIndex()); - assertEquals(true, it.hasPrevious()); + assertTrue(it.hasPrevious()); assertEquals(0, it.previousIndex()); assertEquals("One", it.previous()); assertEquals("Two", it.previous()); diff --git a/src/test/java/org/apache/commons/collections4/iterators/SkippingIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/SkippingIteratorTest.java index af96438986..f9b1d63b14 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/SkippingIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/SkippingIteratorTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -83,11 +89,10 @@ public void testSkipping() { assertEquals("g", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -115,11 +120,10 @@ public void testSameAsDecorated() { assertEquals("g", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -131,11 +135,10 @@ public void testSameAsDecorated() { public void testOffsetGreaterThanSize() { final Iterator iter = new SkippingIterator<>(testList.iterator(), 10); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -144,11 +147,10 @@ public void testOffsetGreaterThanSize() { */ @Test public void testNegativeOffset() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new SkippingIterator<>(testList.iterator(), -1); - fail("Expected IllegalArgumentException."); - } catch (final IllegalArgumentException iae) { /* Success case */ - } + }); + assertTrue(exception.getMessage().contains("Offset parameter must not be negative")); } /** @@ -160,11 +162,10 @@ public void testRemoveWithoutCallingNext() { final List testListCopy = new ArrayList<>(testList); final Iterator iter = new SkippingIterator<>(testListCopy.iterator(), 1); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("Expected IllegalStateException."); - } catch (final IllegalStateException ise) { /* Success case */ - } + }); + assertTrue(exception.getMessage().contains("remove() can not be called before calling next()")); } /** @@ -180,11 +181,10 @@ public void testRemoveCalledTwice() { assertEquals("b", iter.next()); iter.remove(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { iter.remove(); - fail("Expected IllegalStateException."); - } catch (final IllegalStateException ise) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -208,11 +208,10 @@ public void testRemoveFirst() { assertEquals("g", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -238,11 +237,10 @@ public void testRemoveMiddle() { assertEquals("g", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -260,21 +258,19 @@ public void testRemoveLast() { assertEquals("g", iter.next()); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); iter.remove(); assertFalse(testListCopy.contains("g")); assertFalse(iter.hasNext()); - try { + exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Expected NoSuchElementException."); - } catch (final NoSuchElementException nsee) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } /** @@ -293,10 +289,9 @@ public void remove() { final Iterator iter = new SkippingIterator<>(mockIterator, 1); assertTrue(iter.hasNext()); assertEquals("b", iter.next()); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { iter.remove(); - fail("Expected UnsupportedOperationException."); - } catch (final UnsupportedOperationException usoe) { /* Success case */ - } + }); + assertNull(exception.getMessage()); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableIteratorTest.java index 6ba8fd9f5f..936bd72345 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableIteratorTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -74,10 +78,10 @@ public void testDecorateFactory() { it = testList.iterator(); assertTrue(it != UnmodifiableIterator.unmodifiableIterator(it)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableIterator.unmodifiableIterator(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("iterator")); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableListIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableListIteratorTest.java index 7f6ca26156..1573b876fb 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableListIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableListIteratorTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -84,10 +88,10 @@ public void testDecorateFactory() { it = testList.listIterator(); assertTrue(it != UnmodifiableListIterator.umodifiableListIterator(it)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableListIterator.umodifiableListIterator(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("iterator")); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableMapIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableMapIteratorTest.java index 03da805140..96ac0a4a46 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableMapIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableMapIteratorTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; @@ -86,10 +90,10 @@ public void testDecorateFactory() { it = getMap().mapIterator(); assertTrue(it != UnmodifiableMapIterator.unmodifiableMapIterator(it)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableMapIterator.unmodifiableMapIterator(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("iterator")); } } diff --git a/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableOrderedMapIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableOrderedMapIteratorTest.java index c35e9c43d9..ee7c8bdf9e 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableOrderedMapIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/UnmodifiableOrderedMapIteratorTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.iterators; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; import java.util.TreeMap; @@ -88,10 +92,10 @@ public void testDecorateFactory() { it = getMap().mapIterator(); assertTrue(it != UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(it)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableOrderedMapIterator.unmodifiableOrderedMapIterator(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("iterator")); } } diff --git a/src/test/java/org/apache/commons/collections4/keyvalue/AbstractMapEntryTest.java b/src/test/java/org/apache/commons/collections4/keyvalue/AbstractMapEntryTest.java index 4ad9851f2d..9e2c0ce5a7 100644 --- a/src/test/java/org/apache/commons/collections4/keyvalue/AbstractMapEntryTest.java +++ b/src/test/java/org/apache/commons/collections4/keyvalue/AbstractMapEntryTest.java @@ -16,11 +16,15 @@ */ package org.apache.commons.collections4.keyvalue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; import org.junit.Test; -import static org.junit.Assert.*; /** * Abstract tests that can be extended to test any Map.Entry implementation. @@ -83,10 +87,10 @@ public void testAccessorsAndMutators() { // check that null doesn't do anything funny entry = makeMapEntry(null, null); - assertTrue(entry.getKey() == null); + assertNull(entry.getKey()); entry.setValue(null); - assertTrue(entry.getValue() == null); + assertNull(entry.getValue()); } /** @@ -105,15 +109,13 @@ public void testSelfReferenceHandling() { final Map.Entry entry = makeMapEntry(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { entry.setValue((V) entry); - fail("Should throw an IllegalArgumentException"); - } catch (final IllegalArgumentException iae) { - // expected to happen... - - // check that the KVP's state has not changed - assertTrue(entry.getKey() == null && entry.getValue() == null); - } + }); + assertTrue(exception.getMessage().contains("Cannot set value to this map entry")); + // expected to happen... + // check that the KVP's state has not changed + assertTrue(entry.getKey() == null && entry.getValue() == null); } /** @@ -129,18 +131,18 @@ public void testEqualsAndHashCode() { Map.Entry e1 = makeMapEntry((K) key, (V) value); Map.Entry e2 = makeKnownMapEntry((K) key, (V) value); - assertTrue(e1.equals(e1)); - assertTrue(e2.equals(e1)); - assertTrue(e1.equals(e2)); + assertEquals(e1, e1); + assertEquals(e2, e1); + assertEquals(e1, e2); assertTrue(e1.hashCode() == e2.hashCode()); // 2. test with nulls e1 = makeMapEntry(); e2 = makeKnownMapEntry(); - assertTrue(e1.equals(e1)); - assertTrue(e2.equals(e1)); - assertTrue(e1.equals(e2)); + assertEquals(e1, e1); + assertEquals(e2, e1); + assertEquals(e1, e2); assertTrue(e1.hashCode() == e2.hashCode()); } @@ -148,11 +150,11 @@ public void testEqualsAndHashCode() { @Test public void testToString() { Map.Entry entry = makeMapEntry((K) key, (V) value); - assertTrue(entry.toString().equals(entry.getKey() + "=" + entry.getValue())); + assertEquals(entry.toString(), entry.getKey() + "=" + entry.getValue()); // test with nulls entry = makeMapEntry(); - assertTrue(entry.toString().equals(entry.getKey() + "=" + entry.getValue())); + assertEquals(entry.toString(), entry.getKey() + "=" + entry.getValue()); } } diff --git a/src/test/java/org/apache/commons/collections4/keyvalue/DefaultKeyValueTest.java b/src/test/java/org/apache/commons/collections4/keyvalue/DefaultKeyValueTest.java index 9a83655004..84e04850e8 100644 --- a/src/test/java/org/apache/commons/collections4/keyvalue/DefaultKeyValueTest.java +++ b/src/test/java/org/apache/commons/collections4/keyvalue/DefaultKeyValueTest.java @@ -16,12 +16,17 @@ */ package org.apache.commons.collections4.keyvalue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.Test; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.*; + /** * Test the DefaultKeyValue class. @@ -66,10 +71,10 @@ public void testAccessorsAndMutators() { // check that null doesn't do anything funny kv.setKey(null); - assertTrue(kv.getKey() == null); + assertNull(kv.getKey()); kv.setValue(null); - assertTrue(kv.getValue() == null); + assertNull(kv.getValue()); } @@ -82,25 +87,23 @@ public void testSelfReferenceHandling() { final DefaultKeyValue kv = makeDefaultKeyValue(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { kv.setKey((K) kv); - fail("Should throw an IllegalArgumentException"); - } catch (final IllegalArgumentException iae) { - // expected to happen... + }); + assertTrue(exception.getMessage().contains("DefaultKeyValue may not contain itself as a key.")); + // expected to happen... - // check that the KVP's state has not changed - assertTrue(kv.getKey() == null && kv.getValue() == null); - } + // check that the KVP's state has not changed + assertTrue(kv.getKey() == null && kv.getValue() == null); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { kv.setValue((V) kv); - fail("Should throw an IllegalArgumentException"); - } catch (final IllegalArgumentException iae) { - // expected to happen... + }); + assertTrue(exception.getMessage().contains("DefaultKeyValue may not contain itself as a value.")); + // expected to happen... - // check that the KVP's state has not changed - assertTrue(kv.getKey() == null && kv.getValue() == null); - } + // check that the KVP's state has not changed + assertTrue(kv.getKey() == null && kv.getValue() == null); } /** @@ -148,16 +151,16 @@ public void testEqualsAndHashCode() { DefaultKeyValue kv = makeDefaultKeyValue((K) key, (V) value); DefaultKeyValue kv2 = makeDefaultKeyValue((K) key, (V) value); - assertTrue(kv.equals(kv)); - assertTrue(kv.equals(kv2)); + assertEquals(kv, kv); + assertEquals(kv, kv2); assertTrue(kv.hashCode() == kv2.hashCode()); // 2. test with nulls kv = makeDefaultKeyValue(null, null); kv2 = makeDefaultKeyValue(null, null); - assertTrue(kv.equals(kv)); - assertTrue(kv.equals(kv2)); + assertEquals(kv, kv); + assertEquals(kv, kv2); assertTrue(kv.hashCode() == kv2.hashCode()); } @@ -181,7 +184,7 @@ public void testToMapEntry() { map.put(kv.getKey(), kv.getValue()); final Map.Entry entry = map.entrySet().iterator().next(); - assertTrue(entry.equals(kv.toMapEntry())); + assertEquals(entry, kv.toMapEntry()); assertTrue(entry.hashCode() == kv.hashCode()); } diff --git a/src/test/java/org/apache/commons/collections4/keyvalue/DefaultMapEntryTest.java b/src/test/java/org/apache/commons/collections4/keyvalue/DefaultMapEntryTest.java index 1fe8b40272..89cd2787f9 100644 --- a/src/test/java/org/apache/commons/collections4/keyvalue/DefaultMapEntryTest.java +++ b/src/test/java/org/apache/commons/collections4/keyvalue/DefaultMapEntryTest.java @@ -16,12 +16,13 @@ */ package org.apache.commons.collections4.keyvalue; +import static org.junit.Assert.assertSame; + import java.util.Map; import org.apache.commons.collections4.KeyValue; import org.junit.Test; -import static org.junit.Assert.*; /** * Test the DefaultMapEntry class. @@ -85,13 +86,7 @@ public void testConstructors() { public void testSelfReferenceHandling() { final Map.Entry entry = makeMapEntry(); - try { - entry.setValue((V) entry); - assertSame(entry, entry.getValue()); - - } catch (final Exception e) { - fail("This Map.Entry implementation supports value self-reference."); - } + entry.setValue((V) entry); + assertSame(entry, entry.getValue()); } - } diff --git a/src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.java b/src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.java index 0eec7747fd..8590bc18ec 100644 --- a/src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.java +++ b/src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.java @@ -16,6 +16,13 @@ */ package org.apache.commons.collections4.keyvalue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.junit.Test; import java.io.ByteArrayInputStream; @@ -28,7 +35,6 @@ import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.*; /** * Unit tests for {@link org.apache.commons.collections4.keyvalue.MultiKey}. @@ -137,18 +143,18 @@ public void testConstructorsByArray() throws Exception { @Test public void testConstructorsByArrayNull() throws Exception { final Integer[] keys = null; - try { + Exception exception = assertThrows(NullPointerException.class, () -> { new MultiKey<>(keys); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("keys")); + exception = assertThrows(NullPointerException.class, () -> { new MultiKey<>(keys, true); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("keys")); + exception = assertThrows(NullPointerException.class, () -> { new MultiKey<>(keys, false); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("keys")); } @Test @@ -215,14 +221,14 @@ public void testGetIndexed() { final MultiKey mk = new MultiKey<>(ONE, TWO); assertSame(ONE, mk.getKey(0)); assertSame(TWO, mk.getKey(1)); - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { mk.getKey(-1); - fail(); - } catch (final IndexOutOfBoundsException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("-1")); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { mk.getKey(2); - fail(); - } catch (final IndexOutOfBoundsException ex) {} + }); + assertTrue(exception.getMessage().contains("2")); } @Test diff --git a/src/test/java/org/apache/commons/collections4/keyvalue/UnmodifiableMapEntryTest.java b/src/test/java/org/apache/commons/collections4/keyvalue/UnmodifiableMapEntryTest.java index 00ecf528b3..3c0ba8edd5 100644 --- a/src/test/java/org/apache/commons/collections4/keyvalue/UnmodifiableMapEntryTest.java +++ b/src/test/java/org/apache/commons/collections4/keyvalue/UnmodifiableMapEntryTest.java @@ -16,13 +16,16 @@ */ package org.apache.commons.collections4.keyvalue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.Assert.assertSame; + import java.util.Map; import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.Unmodifiable; import org.junit.Test; -import static org.junit.Assert.*; /** * Test the UnmodifiableMapEntry class. @@ -103,10 +106,10 @@ public void testSelfReferenceHandling() { @Test public void testUnmodifiable() { final Map.Entry entry = makeMapEntry(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { entry.setValue(null); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertTrue(exception.getMessage().contains("setValue() is not supported")); } } diff --git a/src/test/java/org/apache/commons/collections4/list/AbstractLinkedListTest.java b/src/test/java/org/apache/commons/collections4/list/AbstractLinkedListTest.java index 395ad8aa92..da3ad2bf3b 100644 --- a/src/test/java/org/apache/commons/collections4/list/AbstractLinkedListTest.java +++ b/src/test/java/org/apache/commons/collections4/list/AbstractLinkedListTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.list; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; /** @@ -139,36 +143,28 @@ public void testGetNode() { final AbstractLinkedList list = getCollection(); // get marker assertEquals(list.getNode(0, true).previous, list.getNode(0, true).next); - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.getNode(0, false); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Couldn't get the node: index (0) is the size of the list.")); list.addAll( Arrays.asList((E[]) new String[]{"value1", "value2"})); checkNodes(); list.addFirst((E) "value0"); checkNodes(); list.removeNode(list.getNode(1, false)); checkNodes(); - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.getNode(2, false); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException ex) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("Couldn't get the node: index")); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.getNode(-1, false); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException ex) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("Couldn't get the node: index")); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.getNode(3, true); - fail("Expecting IndexOutOfBoundsException."); - } catch (final IndexOutOfBoundsException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Couldn't get the node: index")); } protected void checkNodes() { diff --git a/src/test/java/org/apache/commons/collections4/list/AbstractListTest.java b/src/test/java/org/apache/commons/collections4/list/AbstractListTest.java index b0b55e7bc7..5e0ea732a1 100644 --- a/src/test/java/org/apache/commons/collections4/list/AbstractListTest.java +++ b/src/test/java/org/apache/commons/collections4/list/AbstractListTest.java @@ -16,16 +16,21 @@ */ package org.apache.commons.collections4.list; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.Serializable; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.ListIterator; @@ -183,39 +188,36 @@ public void testListAddByIndexBoundsChecking() { return; } - List list; + final List list; final E element = getOtherElements()[0]; - try { - list = makeObject(); + list = makeObject(); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.add(Integer.MIN_VALUE, element); - fail("List.add should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { - list = makeObject(); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.add(-1, element); - fail("List.add should throw IndexOutOfBoundsException [-1]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { - list = makeObject(); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.add(1, element); - fail("List.add should throw IndexOutOfBoundsException [1]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { - list = makeObject(); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.add(Integer.MAX_VALUE, element); - fail("List.add should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } @@ -228,40 +230,28 @@ public void testListAddByIndexBoundsChecking2() { return; } - List list; + final List list = makeFullCollection(); final E element = getOtherElements()[0]; - try { - list = makeFullCollection(); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.add(Integer.MIN_VALUE, element); - fail("List.add should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); - try { - list = makeFullCollection(); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.add(-1, element); - fail("List.add should throw IndexOutOfBoundsException [-1]"); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); - try { - list = makeFullCollection(); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.add(list.size() + 1, element); - fail("List.add should throw IndexOutOfBoundsException [size + 1]"); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); - try { - list = makeFullCollection(); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.add(Integer.MAX_VALUE, element); - fail("List.add should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); } /** @@ -392,39 +382,35 @@ public void testListGetByIndex() { public void testListGetByIndexBoundsChecking() { final List list = makeObject(); - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(Integer.MIN_VALUE); - fail("List.get should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(-1); - fail("List.get should throw IndexOutOfBoundsException [-1]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(0); - fail("List.get should throw IndexOutOfBoundsException [0]"); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(1); - fail("List.get should throw IndexOutOfBoundsException [1]"); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(Integer.MAX_VALUE); - fail("List.get should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } @@ -435,33 +421,29 @@ public void testListGetByIndexBoundsChecking() { public void testListGetByIndexBoundsChecking2() { final List list = makeFullCollection(); - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(Integer.MIN_VALUE); - fail("List.get should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(-1); - fail("List.get should throw IndexOutOfBoundsException [-1]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(getFullElements().length); - fail("List.get should throw IndexOutOfBoundsException [size]"); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(Integer.MAX_VALUE); - fail("List.get should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); } /** @@ -522,39 +504,38 @@ public void testListSetByIndexBoundsChecking() { final List list = makeObject(); final E element = getOtherElements()[0]; - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(Integer.MIN_VALUE, element); - fail("List.set should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("-2147483648")); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(-1, element); - fail("List.set should throw IndexOutOfBoundsException [-1]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(0, element); - fail("List.set should throw IndexOutOfBoundsException [0]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(1, element); - fail("List.set should throw IndexOutOfBoundsException [1]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(Integer.MAX_VALUE, element); - fail("List.set should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } @@ -571,35 +552,28 @@ public void testListSetByIndexBoundsChecking2() { final List list = makeFullCollection(); final E element = getOtherElements()[0]; - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(Integer.MIN_VALUE, element); - fail("List.set should throw IndexOutOfBoundsException " + - "[Integer.MIN_VALUE]"); - } catch(final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(-1, element); - fail("List.set should throw IndexOutOfBoundsException [-1]"); - } catch(final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(getFullElements().length, element); - fail("List.set should throw IndexOutOfBoundsException [size]"); - } catch(final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(Integer.MAX_VALUE, element); - fail("List.set should throw IndexOutOfBoundsException " + - "[Integer.MAX_VALUE]"); - } catch(final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); } @@ -634,11 +608,11 @@ public void testUnsupportedSet() { } resetFull(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().set(0, getFullElements()[0]); - fail("Emtpy collection should not support set."); - } catch (final UnsupportedOperationException e) { - // expected + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("Index:")); } // make sure things didn't change even if the expected exception was // thrown. @@ -656,40 +630,34 @@ public void testListRemoveByIndexBoundsChecking() { final List list = makeObject(); - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.remove(Integer.MIN_VALUE); - fail("List.remove should throw IndexOutOfBoundsException [Integer.MIN_VALUE]"); - } catch(final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.remove(-1); - fail("List.remove should throw IndexOutOfBoundsException [-1]"); - } catch(final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.remove(0); - fail("List.remove should throw IndexOutOfBoundsException [0]"); - } catch(final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.remove(1); - fail("List.remove should throw IndexOutOfBoundsException [1]"); - } catch(final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.remove(Integer.MAX_VALUE); - fail("List.remove should throw IndexOutOfBoundsException [Integer.MAX_VALUE]"); - } catch(final IndexOutOfBoundsException e) { - // expected - } + }); + assertNotNull(exception.getMessage()); } /** @@ -703,34 +671,32 @@ public void testListRemoveByIndexBoundsChecking2() { final List list = makeFullCollection(); - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.remove(Integer.MIN_VALUE); - fail("List.remove should throw IndexOutOfBoundsException " + - "[Integer.MIN_VALUE]"); - } catch(final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.remove(-1); - fail("List.remove should throw IndexOutOfBoundsException [-1]"); - } catch(final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.remove(getFullElements().length); - fail("List.remove should throw IndexOutOfBoundsException [size]"); - } catch(final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.remove(Integer.MAX_VALUE); - fail("List.remove should throw IndexOutOfBoundsException " + - "[Integer.MAX_VALUE]"); - } catch(final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } @@ -846,7 +812,7 @@ public void testListListIteratorPreviousRemovePrevious() { assertEquals(two, getCollection().get(1)); final E zero3 = it.previous(); // do previous after remove assertEquals(zero, zero3); - assertEquals(false, it.hasPrevious()); + assertFalse(it.hasPrevious()); assertEquals(getCollection().size() > 2, it.hasNext()); } @@ -876,7 +842,7 @@ public void testListListIteratorNextRemoveNext() { final E three2 = it.next(); // do next after remove assertEquals(three, three2); assertEquals(getCollection().size() > 3, it.hasNext()); - assertEquals(true, it.hasPrevious()); + assertTrue(it.hasPrevious()); } /** @@ -903,8 +869,8 @@ public void testListListIteratorNextRemovePrevious() { assertEquals(one, getCollection().get(1)); final E one2 = it.previous(); // do previous after remove assertEquals(one, one2); - assertEquals(true, it.hasNext()); - assertEquals(true, it.hasPrevious()); + assertTrue(it.hasNext()); + assertTrue(it.hasPrevious()); } //----------------------------------------------------------------------- @@ -919,7 +885,7 @@ private void forwardTest(final ListIterator iter, int i) { final int max = getFullElements().length; while (i < max) { - assertTrue("Iterator should have next", iter.hasNext()); + assertTrue(iter.hasNext()); assertEquals("Iterator.nextIndex should work", i, iter.nextIndex()); assertEquals("Iterator.previousIndex should work", @@ -929,15 +895,15 @@ private void forwardTest(final ListIterator iter, int i) { i++; } - assertTrue("Iterator shouldn't have next", !iter.hasNext()); + assertTrue(!iter.hasNext()); assertEquals("nextIndex should be size", max, iter.nextIndex()); assertEquals("previousIndex should be size - 1", max - 1, iter.previousIndex()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Exhausted iterator should raise NoSuchElement"); - } catch (final NoSuchElementException e) { - // expected + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("No element at index")); } } @@ -951,8 +917,7 @@ private void backwardTest(final ListIterator iter, int i) { final List list = getCollection(); while (i > 0) { - assertTrue("Iterator should have previous, i:" + i, - iter.hasPrevious()); + assertTrue(iter.hasPrevious()); assertEquals("Iterator.nextIndex should work, i:" + i, i, iter.nextIndex()); assertEquals("Iterator.previousIndex should work, i:" + i, @@ -963,19 +928,18 @@ private void backwardTest(final ListIterator iter, int i) { i--; } - assertTrue("Iterator shouldn't have previous", !iter.hasPrevious()); + assertTrue(!iter.hasPrevious()); final int nextIndex = iter.nextIndex(); assertEquals("nextIndex should be 0", 0, nextIndex); final int prevIndex = iter.previousIndex(); assertEquals("previousIndex should be -1", -1, prevIndex); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.previous(); - fail("Exhausted iterator should raise NoSuchElement"); - } catch (final NoSuchElementException e) { - // expected + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("Already at start of list.")); } - } @@ -1327,19 +1291,10 @@ protected void failFastMethod(final List list, final Method m) { } } - try { + Exception exception = assertThrows(Exception.class, () -> { m.invoke(list, params); - fail(m.getName() + " should raise ConcurrentModification"); - } catch (final IllegalAccessException e) { - // impossible - } catch (final InvocationTargetException e) { - final Throwable t = e.getTargetException(); - if (t instanceof ConcurrentModificationException) { - // expected - return; - } - fail(m.getName() + " raised unexpected " + e); - } + }); + assertNull(exception.getMessage()); } // ----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/list/CursorableLinkedListTest.java b/src/test/java/org/apache/commons/collections4/list/CursorableLinkedListTest.java index b0e4d8e6c2..aad11a1fd9 100644 --- a/src/test/java/org/apache/commons/collections4/list/CursorableLinkedListTest.java +++ b/src/test/java/org/apache/commons/collections4/list/CursorableLinkedListTest.java @@ -16,6 +16,13 @@ */ package org.apache.commons.collections4.list; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.HashSet; @@ -246,12 +253,10 @@ public void testCursorRemove() { list.add((E) "5"); final CursorableLinkedList.Cursor it = list.cursor(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail(); - } catch (final IllegalStateException e) { - // expected - } + }); + assertNull(exception.getMessage()); assertEquals("1", it.next()); assertEquals("2", it.next()); assertEquals("[1, 2, 3, 4, 5]", list.toString()); @@ -266,11 +271,10 @@ public void testCursorRemove() { assertEquals("3", it.next()); it.remove(); assertEquals("[4, 5]", list.toString()); - try { + exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - } catch (final IllegalStateException e) { - // expected - } + }); + assertNull(exception.getMessage()); assertEquals("4", it.next()); assertEquals("5", it.next()); it.remove(); @@ -352,17 +356,15 @@ public void testCursorConcurrentModification() { assertEquals("9", c2.next()); assertEquals("10", c2.next()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { c2.next(); - fail(); - } catch (final NoSuchElementException nse) { - } + }); + assertTrue(exception.getMessage().contains("No element at index 7.")); - try { + exception = assertThrows(ConcurrentModificationException.class, () -> { li.next(); - fail(); - } catch (final ConcurrentModificationException cme) { - } + }); + assertNull(exception.getMessage()); c1.close(); // not necessary c2.close(); // not necessary @@ -470,19 +472,19 @@ public void testInternalState_CursorNextNextPreviousRemoveIndex1ByList() { assertEquals("B", list.remove(1)); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(1, c1.nextIndex); - assertEquals(true, c1.currentRemovedByAnother); - assertEquals(null, c1.current); + assertTrue(c1.currentRemovedByAnother); + assertNull(c1.current); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -496,19 +498,19 @@ public void testInternalState_CursorNextRemoveIndex1ByList() { assertEquals("B", list.remove(1)); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(1, c1.nextIndex); - assertEquals(false, c1.currentRemovedByAnother); + assertFalse(c1.currentRemovedByAnother); assertEquals("A", c1.current.value); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); c1.remove(); // works ok assertEquals("[C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -523,19 +525,19 @@ public void testInternalState_CursorNextNextRemoveIndex1ByList() { assertEquals("B", list.remove(1)); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(1, c1.nextIndex); - assertEquals(true, c1.currentRemovedByAnother); - assertEquals(null, c1.current); + assertTrue(c1.currentRemovedByAnother); + assertNull(c1.current); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -552,18 +554,18 @@ public void testInternalState_CursorNextNextNextRemoveIndex1ByList() { assertEquals("B", list.remove(1)); - assertEquals(false, c1.nextIndexValid); - assertEquals(false, c1.currentRemovedByAnother); + assertFalse(c1.nextIndexValid); + assertFalse(c1.currentRemovedByAnother); assertEquals("C", c1.current.value); assertEquals("D", c1.next.value); assertEquals("[A, C, D]", list.toString()); c1.remove(); // works ok assertEquals("[A, D]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } //----------------------------------------------------------------------- @@ -580,17 +582,17 @@ public void testInternalState_CursorNextNextPreviousRemoveByIterator() { c1.remove(); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(1, c1.nextIndex); - assertEquals(false, c1.currentRemovedByAnother); - assertEquals(null, c1.current); + assertFalse(c1.currentRemovedByAnother); + assertNull(c1.current); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -605,17 +607,17 @@ public void testInternalState_CursorNextNextRemoveByIterator() { c1.remove(); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(1, c1.nextIndex); - assertEquals(false, c1.currentRemovedByAnother); - assertEquals(null, c1.current); + assertFalse(c1.currentRemovedByAnother); + assertNull(c1.current); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } //----------------------------------------------------------------------- @@ -632,7 +634,7 @@ public void testInternalState_CursorNextNextPreviousAddIndex1ByList() { list.add(1, (E) "Z"); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals("B", c1.current.value); assertEquals("Z", c1.next.value); @@ -640,10 +642,10 @@ public void testInternalState_CursorNextNextPreviousAddIndex1ByList() { assertEquals("[A, Z, B, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, Z, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -657,7 +659,7 @@ public void testInternalState_CursorNextAddIndex1ByList() { list.add(1, (E) "Z"); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals("A", c1.current.value); assertEquals("Z", c1.next.value); @@ -665,10 +667,10 @@ public void testInternalState_CursorNextAddIndex1ByList() { assertEquals("[A, Z, B, C]", list.toString()); c1.remove(); // works ok assertEquals("[Z, B, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -683,17 +685,17 @@ public void testInternalState_CursorNextNextAddIndex1ByList() { list.add(1, (E) "Z"); - assertEquals(false, c1.nextIndexValid); + assertFalse(c1.nextIndexValid); assertEquals("B", c1.current.value); assertEquals("C", c1.next.value); assertEquals("[A, Z, B, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, Z, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } //----------------------------------------------------------------------- @@ -710,16 +712,16 @@ public void testInternalState_CursorNextNextPreviousAddByIterator() { c1.add((E) "Z"); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(2, c1.nextIndex); - assertEquals(null, c1.current); + assertNull(c1.current); assertEquals("B", c1.next.value); assertEquals("[A, Z, B, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -734,17 +736,17 @@ public void testInternalState_CursorNextNextAddByIterator() { c1.add((E) "Z"); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(3, c1.nextIndex); - assertEquals(false, c1.currentRemovedByAnother); - assertEquals(null, c1.current); + assertFalse(c1.currentRemovedByAnother); + assertNull(c1.current); assertEquals("C", c1.next.value); assertEquals("[A, B, Z, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } //----------------------------------------------------------------------- @@ -760,16 +762,16 @@ public void testInternalState_CursorNextNextRemoveByListSetByIterator() { list.remove(1); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(1, c1.nextIndex); - assertEquals(null, c1.current); + assertNull(c1.current); assertEquals("C", c1.next.value); assertEquals("[A, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.set((E) "Z"); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } //----------------------------------------------------------------------- @@ -786,7 +788,7 @@ public void testInternalState_CursorNextNextPreviousSetByIterator() { c1.set((E) "Z"); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(1, c1.nextIndex); assertEquals("Z", c1.current.value); assertEquals("Z", c1.next.value); @@ -794,10 +796,10 @@ public void testInternalState_CursorNextNextPreviousSetByIterator() { assertEquals("[A, Z, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -812,7 +814,7 @@ public void testInternalState_CursorNextNextSetByIterator() { c1.set((E) "Z"); - assertEquals(true, c1.nextIndexValid); + assertTrue(c1.nextIndexValid); assertEquals(2, c1.nextIndex); assertEquals("Z", c1.current.value); assertEquals("C", c1.next.value); @@ -820,10 +822,10 @@ public void testInternalState_CursorNextNextSetByIterator() { assertEquals("[A, Z, C]", list.toString()); c1.remove(); // works ok assertEquals("[A, C]", list.toString()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { c1.remove(); - fail(); - } catch (final IllegalStateException ex) {} + }); + assertNull(exception.getMessage()); } //----------------------------------------------------------------------- @@ -893,12 +895,10 @@ public void testEqualsAndHashCode() { @SuppressWarnings("unchecked") public void testGet() { - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(0); - fail("shouldn't get here"); - } catch(final IndexOutOfBoundsException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Couldn't get the node: index (0) is the size of the list")); assertTrue(list.add((E) "A")); assertEquals("A", list.get(0)); @@ -906,19 +906,15 @@ public void testGet() { assertEquals("A", list.get(0)); assertEquals("B", list.get(1)); - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(-1); - fail("shouldn't get here"); - } catch(final IndexOutOfBoundsException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Couldn't get the node: index (-1) ")); - try { + exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.get(2); - fail("shouldn't get here"); - } catch(final IndexOutOfBoundsException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Couldn't get the node: index (2) ")); } @SuppressWarnings("unchecked") diff --git a/src/test/java/org/apache/commons/collections4/list/FixedSizeListTest.java b/src/test/java/org/apache/commons/collections4/list/FixedSizeListTest.java index a4f60f9d0e..6ee46a5170 100644 --- a/src/test/java/org/apache/commons/collections4/list/FixedSizeListTest.java +++ b/src/test/java/org/apache/commons/collections4/list/FixedSizeListTest.java @@ -16,7 +16,11 @@ */ package org.apache.commons.collections4.list; -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; @@ -78,9 +82,9 @@ public void testListAllowsMutationOfUnderlyingCollection() { final int sizeBefore = fixedSizeList.size(); // final boolean changed = decoratedList.add("New Value"); - Assert.assertTrue(changed); + assertTrue(changed); // - Assert.assertEquals("Modifying an the underlying list is allowed", + assertEquals("Modifying an the underlying list is allowed", sizeBefore + 1, fixedSizeList.size()); } @@ -95,10 +99,10 @@ private FixedSizeList initFixedSizeList() { public void testAdd() { final FixedSizeList fixedSizeList = initFixedSizeList(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { fixedSizeList.add(2, "New Value"); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertTrue(exception.getMessage().contains("List is fixed size")); } @@ -109,38 +113,38 @@ public void testAddAll() { addList.add("item 3"); addList.add("item 4"); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { fixedSizeList.addAll(2, addList); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertTrue(exception.getMessage().contains("List is fixed size")); } public void testRemove() { final FixedSizeList fixedSizeList = initFixedSizeList(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { fixedSizeList.remove(1); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertTrue(exception.getMessage().contains("List is fixed size")); } public void testSubList() { final FixedSizeList fixedSizeList = initFixedSizeList(); final List subFixedSizeList = fixedSizeList.subList(1, 1); - Assert.assertNotNull(subFixedSizeList); - Assert.assertEquals(0, subFixedSizeList.size()); + assertNotNull(subFixedSizeList); + assertEquals(0, subFixedSizeList.size()); } public void testIsFull() { final FixedSizeList fixedSizeList = initFixedSizeList(); - Assert.assertTrue(fixedSizeList.isFull()); + assertTrue(fixedSizeList.isFull()); } public void testMaxSize() { final FixedSizeList fixedSizeList = initFixedSizeList(); - Assert.assertEquals(2, fixedSizeList.maxSize()); + assertEquals(2, fixedSizeList.maxSize()); } } diff --git a/src/test/java/org/apache/commons/collections4/list/GrowthListTest.java b/src/test/java/org/apache/commons/collections4/list/GrowthListTest.java index 61f5f656a6..6d14c112b0 100644 --- a/src/test/java/org/apache/commons/collections4/list/GrowthListTest.java +++ b/src/test/java/org/apache/commons/collections4/list/GrowthListTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.list; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -66,7 +71,7 @@ public void testGrowthAdd() { assertEquals(0, grower.size()); grower.add(1, one); assertEquals(2, grower.size()); - assertEquals(null, grower.get(0)); + assertNull(grower.get(0)); assertEquals(one, grower.get(1)); } @@ -80,7 +85,7 @@ public void testGrowthAddAll() { assertEquals(0, grower.size()); grower.addAll(1, coll); assertEquals(3, grower.size()); - assertEquals(null, grower.get(0)); + assertNull(grower.get(0)); assertEquals(one, grower.get(1)); assertEquals(two, grower.get(2)); } @@ -91,7 +96,7 @@ public void testGrowthSet1() { assertEquals(0, grower.size()); grower.set(1, one); assertEquals(2, grower.size()); - assertEquals(null, grower.get(0)); + assertNull(grower.get(0)); assertEquals(one, grower.get(1)); } @@ -110,15 +115,13 @@ public void testGrowthSet2() { */ @Override public void testListAddByIndexBoundsChecking() { - List list; + final List list; final E element = getOtherElements()[0]; - try { - list = makeObject(); + list = makeObject(); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.add(-1, element); - fail("List.add should throw IndexOutOfBoundsException [-1]"); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Index: -1, Size: 0")); } /** @@ -126,15 +129,13 @@ public void testListAddByIndexBoundsChecking() { */ @Override public void testListAddByIndexBoundsChecking2() { - List list; + final List list; final E element = getOtherElements()[0]; - try { - list = makeFullCollection(); + list = makeFullCollection(); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.add(-1, element); - fail("List.add should throw IndexOutOfBoundsException [-1]"); - } catch (final IndexOutOfBoundsException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Index: -1, Size: ")); } /** @@ -144,11 +145,11 @@ public void testListAddByIndexBoundsChecking2() { public void testListSetByIndexBoundsChecking() { final List list = makeObject(); final E element = getOtherElements()[0]; - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(-1, element); - fail("List.set should throw IndexOutOfBoundsException [-1]"); - } catch (final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("-1")); } } @@ -159,11 +160,11 @@ public void testListSetByIndexBoundsChecking() { public void testListSetByIndexBoundsChecking2() { final List list = makeFullCollection(); final E element = getOtherElements()[0]; - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { list.set(-1, element); - fail("List.set should throw IndexOutOfBoundsException [-1]"); - } catch(final IndexOutOfBoundsException e) { - // expected + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("-1")); } } diff --git a/src/test/java/org/apache/commons/collections4/list/PredicatedListTest.java b/src/test/java/org/apache/commons/collections4/list/PredicatedListTest.java index 88e60ebb13..23012a0f51 100644 --- a/src/test/java/org/apache/commons/collections4/list/PredicatedListTest.java +++ b/src/test/java/org/apache/commons/collections4/list/PredicatedListTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.list; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.List; @@ -66,13 +71,11 @@ public List makeTestList() { public void testIllegalAdd() { final List list = makeTestList(); final Integer i = Integer.valueOf(3); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { list.add((E) i); - fail("Integer should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - assertTrue("Collection shouldn't contain illegal element", !list.contains(i)); + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3'")); + assertTrue(!list.contains(i)); } @SuppressWarnings("unchecked") @@ -83,27 +86,23 @@ public void testIllegalAddAll() { elements.add((E) "two"); elements.add((E) Integer.valueOf(3)); elements.add((E) "four"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { list.addAll(0, elements); - fail("Integer should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - assertTrue("List shouldn't contain illegal element", !list.contains("one")); - assertTrue("List shouldn't contain illegal element", !list.contains("two")); - assertTrue("List shouldn't contain illegal element", !list.contains(Integer.valueOf(3))); - assertTrue("List shouldn't contain illegal element", !list.contains("four")); + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3'")); + assertTrue(!list.contains("one")); + assertTrue(!list.contains("two")); + assertTrue(!list.contains(Integer.valueOf(3))); + assertTrue(!list.contains("four")); } @SuppressWarnings("unchecked") public void testIllegalSet() { final List list = makeTestList(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { list.set(0, (E) Integer.valueOf(3)); - fail("Integer should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3'")); } @SuppressWarnings("unchecked") @@ -115,10 +114,10 @@ public void testLegalAddAll() { elements.add((E) "two"); elements.add((E) "three"); list.addAll(1, elements); - assertTrue("List should contain legal element", list.contains("zero")); - assertTrue("List should contain legal element", list.contains("one")); - assertTrue("List should contain legal element", list.contains("two")); - assertTrue("List should contain legal element", list.contains("three")); + assertTrue(list.contains("zero")); + assertTrue(list.contains("one")); + assertTrue(list.contains("two")); + assertTrue(list.contains("three")); } public void testSubList() { diff --git a/src/test/java/org/apache/commons/collections4/list/SetUniqueListTest.java b/src/test/java/org/apache/commons/collections4/list/SetUniqueListTest.java index 4aea06d98d..3d44896425 100644 --- a/src/test/java/org/apache/commons/collections4/list/SetUniqueListTest.java +++ b/src/test/java/org/apache/commons/collections4/list/SetUniqueListTest.java @@ -16,6 +16,13 @@ */ package org.apache.commons.collections4.list; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -119,10 +126,9 @@ public void testCollectionAddAll() { boolean r = getCollection().addAll(Arrays.asList(elements)); getConfirmed().addAll(Arrays.asList(elements)); verify(); - assertTrue("Empty collection should change after addAll", r); + assertTrue(r); for (final E element : elements) { - assertTrue("Collection should contain added element", - getCollection().contains(element)); + assertTrue(getCollection().contains(element)); } resetFull(); @@ -131,10 +137,9 @@ public void testCollectionAddAll() { r = getCollection().addAll(Arrays.asList(elements)); getConfirmed().addAll(Arrays.asList(elements)); verify(); - assertTrue("Full collection should change after addAll", r); + assertTrue(r); for (int i = 0; i < elements.length; i++) { - assertTrue("Full collection should contain added element " + i, - getCollection().contains(elements[i])); + assertTrue(getCollection().contains(elements[i])); } assertEquals("Size should increase after addAll", size + elements.length, getCollection().size()); @@ -334,10 +339,10 @@ public void testListIteratorSet() { resetFull(); final ListIterator it = getCollection().listIterator(); it.next(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { it.set(null); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertTrue(exception.getMessage().contains("ListIterator does not support set")); } @Override @@ -463,8 +468,8 @@ public void testSetCollections444() { public void testSetDownwardsInList() { /* * Checks the following semantics - * [a,b] - * set(0,b): [b]->a + * [a, b] + * set (0, b) : [b] -> a * So UniqList contains [b] and a is returned */ final ArrayList l = new ArrayList<>(); @@ -491,9 +496,9 @@ public void testSetDownwardsInList() { public void testSetInBiggerList() { /* * Checks the following semantics - * [a,b,c] - * set(0,b): [b,c]->a - * So UniqList contains [b,c] and a is returned + * [a, b, c] + * set (0, b) : [b, c] -> a + * So UniqList contains [b, c] and a is returned */ final ArrayList l = new ArrayList<>(); final HashSet s = new HashSet<>(); @@ -562,12 +567,10 @@ public void testSetUpwardsInList() { public void testSubListIsUnmodifiable() { resetFull(); final List subList = getCollection().subList(1, 3); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { subList.remove(0); - fail("subList should be unmodifiable"); - } catch (final UnsupportedOperationException e) { - // expected - } + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") diff --git a/src/test/java/org/apache/commons/collections4/list/UnmodifiableListTest.java b/src/test/java/org/apache/commons/collections4/list/UnmodifiableListTest.java index 670f175b43..15df527eb1 100644 --- a/src/test/java/org/apache/commons/collections4/list/UnmodifiableListTest.java +++ b/src/test/java/org/apache/commons/collections4/list/UnmodifiableListTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.list; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; @@ -85,74 +90,54 @@ public void testDecorateFactory() { final List list = makeObject(); assertSame(list, UnmodifiableList.unmodifiableList(list)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableList.unmodifiableList(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("collection")); } @SuppressWarnings("unchecked") protected void verifyUnmodifiable(final List list) { - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { list.add(0, (E) Integer.valueOf(0)); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { list.add((E) Integer.valueOf(0)); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { list.addAll(0, array); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { list.addAll(array); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { list.clear(); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { list.remove(0); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { list.remove(Integer.valueOf(0)); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { list.removeAll(array); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { list.retainAll(array); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { list.set(0, (E) Integer.valueOf(0)); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } + }); + assertNull(exception.getMessage()); } /** @@ -161,13 +146,11 @@ protected void verifyUnmodifiable(final List list) { public void testUnmodifiableIterator() { setupList(); final Iterator iterator = list.iterator(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { iterator.next(); iterator.remove(); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/map/AbstractIterableMapTest.java b/src/test/java/org/apache/commons/collections4/map/AbstractIterableMapTest.java index 98679bcde1..d76529a3b6 100644 --- a/src/test/java/org/apache/commons/collections4/map/AbstractIterableMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/AbstractIterableMapTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; @@ -63,22 +66,22 @@ public void testFailFastEntrySet() { return; } resetFull(); - Iterator> it = getMap().entrySet().iterator(); - final Map.Entry val = it.next(); + final Iterator> it1 = getMap().entrySet().iterator(); + final Map.Entry val = it1.next(); getMap().remove(val.getKey()); - try { - it.next(); - fail(); - } catch (final ConcurrentModificationException ex) {} + Exception exception = assertThrows(ConcurrentModificationException.class, () -> { + it1.next(); + }); + assertNull(exception.getMessage()); resetFull(); - it = getMap().entrySet().iterator(); + Iterator> it = getMap().entrySet().iterator(); it.next(); getMap().clear(); - try { + exception = assertThrows(ConcurrentModificationException.class, () -> { it.next(); - fail(); - } catch (final ConcurrentModificationException ex) {} + }); + assertNull(exception.getMessage()); } public void testFailFastKeySet() { @@ -89,22 +92,22 @@ public void testFailFastKeySet() { return; } resetFull(); - Iterator it = getMap().keySet().iterator(); - final K val = it.next(); + final Iterator it1 = getMap().keySet().iterator(); + final K val = it1.next(); getMap().remove(val); - try { - it.next(); - fail(); - } catch (final ConcurrentModificationException ex) {} + Exception exception = assertThrows(ConcurrentModificationException.class, () -> { + it1.next(); + }); + assertNull(exception.getMessage()); resetFull(); - it = getMap().keySet().iterator(); + Iterator it = getMap().keySet().iterator(); it.next(); getMap().clear(); - try { + exception = assertThrows(ConcurrentModificationException.class, () -> { it.next(); - fail(); - } catch (final ConcurrentModificationException ex) {} + }); + assertNull(exception.getMessage()); } public void testFailFastValues() { @@ -115,22 +118,22 @@ public void testFailFastValues() { return; } resetFull(); - Iterator it = getMap().values().iterator(); - it.next(); + final Iterator it1 = getMap().values().iterator(); + it1.next(); getMap().remove(getMap().keySet().iterator().next()); - try { - it.next(); - fail(); - } catch (final ConcurrentModificationException ex) {} + Exception exception = assertThrows(ConcurrentModificationException.class, () -> { + it1.next(); + }); + assertNull(exception.getMessage()); resetFull(); - it = getMap().values().iterator(); + Iterator it = getMap().values().iterator(); it.next(); getMap().clear(); - try { + exception = assertThrows(ConcurrentModificationException.class, () -> { it.next(); - fail(); - } catch (final ConcurrentModificationException ex) {} + }); + assertNull(exception.getMessage()); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/map/AbstractMapTest.java b/src/test/java/org/apache/commons/collections4/map/AbstractMapTest.java index a8e5813a7a..2a9fc87346 100644 --- a/src/test/java/org/apache/commons/collections4/map/AbstractMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/AbstractMapTest.java @@ -16,6 +16,13 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; @@ -596,11 +603,13 @@ public void testMapSize() { */ public void testMapClear() { if (!isRemoveSupported()) { - try { - resetFull(); + resetFull(); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { getMap().clear(); - fail("Expected UnsupportedOperationException on clear"); - } catch (final UnsupportedOperationException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("Map is fixed size")); + } return; } @@ -828,21 +837,20 @@ public void testMapPut() { } } } else { - try { - // two possible exception here, either valid + // two possible exception here, either valid + Exception exception = assertThrows(IllegalArgumentException.class, () -> { getMap().put(keys[0], newValues[0]); - fail("Expected IllegalArgumentException or UnsupportedOperationException on put (change)"); - } catch (final IllegalArgumentException ex) { - } catch (final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); } } else if (isPutChangeSupported()) { resetEmpty(); - try { + Exception exception = assertThrows(Exception.class, () -> { getMap().put(keys[0], values[0]); - fail("Expected UnsupportedOperationException or IllegalArgumentException on put (add) when fixed size"); - } catch (final IllegalArgumentException ex) { - } catch (final UnsupportedOperationException ex) { + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("Map is fixed size")); } resetFull(); @@ -866,10 +874,10 @@ public void testMapPut() { } } } else { - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { getMap().put(keys[0], values[0]); - fail("Expected UnsupportedOperationException on put (add)"); - } catch (final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); } } @@ -884,11 +892,12 @@ public void testMapPutNullKey() { if (isAllowNullKey()) { getMap().put(null, values[0]); } else { - try { + Exception exception = assertThrows(Exception.class, () -> { getMap().put(null, values[0]); - fail("put(null, value) should throw NPE/IAE"); - } catch (final NullPointerException ex) { - } catch (final IllegalArgumentException ex) {} + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); + } } } } @@ -904,11 +913,12 @@ public void testMapPutNullValue() { if (isAllowNullValue()) { getMap().put(keys[0], null); } else { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { getMap().put(keys[0], null); - fail("put(key, null) should throw NPE/IAE"); - } catch (final NullPointerException ex) { - } catch (final IllegalArgumentException ex) {} + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); + } } } } @@ -921,10 +931,10 @@ public void testMapPutAll() { if (!isPutChangeSupported()) { final Map temp = makeFullMap(); resetEmpty(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { getMap().putAll(temp); - fail("Expected UnsupportedOperationException on putAll"); - } catch (final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); } return; } @@ -979,11 +989,13 @@ public void testMapPutAll() { */ public void testMapRemove() { if (!isRemoveSupported()) { - try { - resetFull(); + resetFull(); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { getMap().remove(getMap().keySet().iterator().next()); - fail("Expected UnsupportedOperationException on remove"); - } catch (final UnsupportedOperationException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("Map is fixed size")); + } return; } @@ -993,7 +1005,7 @@ public void testMapRemove() { final Object[] values = getSampleValues(); for (final Object key : keys) { final Object o = getMap().remove(key); - assertTrue("First map.remove should return null", o == null); + assertNull(o); } verify(); @@ -1014,7 +1026,7 @@ public void testMapRemove() { final int size = getMap().size(); for (final Object element : other) { final Object o = getMap().remove(element); - assertNull("map.remove for nonexistent key should return null", o); + assertNull(o); assertEquals("map.remove for nonexistent key should not " + "shrink map", size, getMap().size()); } @@ -1215,10 +1227,8 @@ public void testValuesRemoveChangesMap() { } j++; } - assertTrue("values().remove(obj) is broken", j < 10000); - assertTrue( - "Value should have been removed from the underlying map.", - !getMap().containsValue(sampleValue)); + assertTrue(j < 10000); + assertTrue(!getMap().containsValue(sampleValue)); } } } @@ -1322,9 +1332,7 @@ public void testKeySetRemoveChangesMap() { // if key.remove is unsupported, just skip this test return; } - assertTrue( - "Key should have been removed from the underlying map.", - !getMap().containsKey(sampleKey)); + assertTrue(!getMap().containsKey(sampleKey)); } } @@ -1409,9 +1417,7 @@ public void testEntrySetRemoveChangesMap() { // if entrySet removal is unsupported, just skip this test return; } - assertTrue( - "Entry should have been removed from the underlying map.", - !getMap().containsKey(sampleKeys[i])); + assertTrue(!getMap().containsKey(sampleKeys[i])); } } @@ -1962,7 +1968,7 @@ public void verifyMap() { // concurrent modification exceptions. // Because of this we have assertEquals(map, confirmed), and not the other way around. assertEquals("Map should still equal HashMap", map, confirmed); - assertTrue("Map should still equal HashMap", getMap().equals(getConfirmed())); + assertTrue(getMap().equals(getConfirmed())); } public void verifyEntrySet() { @@ -1974,9 +1980,7 @@ public void verifyEntrySet() { assertEquals("entrySet should be empty if HashMap is" + "\nTest: " + entrySet + "\nReal: " + getConfirmed().entrySet(), empty, entrySet.isEmpty()); - assertTrue("entrySet should contain all HashMap's elements" + - "\nTest: " + entrySet + "\nReal: " + getConfirmed().entrySet(), - entrySet.containsAll(getConfirmed().entrySet())); + assertTrue(entrySet.containsAll(getConfirmed().entrySet())); assertEquals("entrySet hashCodes should be the same" + "\nTest: " + entrySet + "\nReal: " + getConfirmed().entrySet(), getConfirmed().entrySet().hashCode(), entrySet.hashCode()); @@ -1993,9 +1997,7 @@ public void verifyKeySet() { assertEquals("keySet should be empty if HashMap is" + "\nTest: " + keySet + "\nReal: " + getConfirmed().keySet(), empty, keySet.isEmpty()); - assertTrue("keySet should contain all HashMap's elements" + - "\nTest: " + keySet + "\nReal: " + getConfirmed().keySet(), - keySet.containsAll(getConfirmed().keySet())); + assertTrue(keySet.containsAll(getConfirmed().keySet())); assertEquals("keySet hashCodes should be the same" + "\nTest: " + keySet + "\nReal: " + getConfirmed().keySet(), getConfirmed().keySet().hashCode(), keySet.hashCode()); @@ -2018,18 +2020,14 @@ public void verifyValues() { assertEquals("values should be empty if HashMap is" + "\nTest: " + test + "\nReal: " + known, empty, values.isEmpty()); - assertTrue("values should contain all HashMap's elements" + - "\nTest: " + test + "\nReal: " + known, - test.containsAll(known)); - assertTrue("values should contain all HashMap's elements" + - "\nTest: " + test + "\nReal: " + known, - known.containsAll(test)); + assertTrue(test.containsAll(known)); + assertTrue(known.containsAll(test)); // originally coded to use a HashBag, but now separate jar so... for (final V v : known) { final boolean removed = test.remove(v); - assertTrue("Map's values should still equal HashMap's", removed); + assertTrue(removed); } - assertTrue("Map's values should still equal HashMap's", test.isEmpty()); + assertTrue(test.isEmpty()); } /** diff --git a/src/test/java/org/apache/commons/collections4/map/AbstractOrderedMapTest.java b/src/test/java/org/apache/commons/collections4/map/AbstractOrderedMapTest.java index c46bceae83..f1e2ee7547 100644 --- a/src/test/java/org/apache/commons/collections4/map/AbstractOrderedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/AbstractOrderedMapTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -86,28 +90,32 @@ public K[] getSampleKeys() { //----------------------------------------------------------------------- public void testFirstKey() { resetEmpty(); - OrderedMap ordered = getMap(); - try { - ordered.firstKey(); - fail(); - } catch (final NoSuchElementException ex) {} + final OrderedMap ordered1 = getMap(); + Exception exception = assertThrows(NoSuchElementException.class, () -> { + ordered1.firstKey(); + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("Map is empty")); + } resetFull(); - ordered = getMap(); + OrderedMap ordered = getMap(); final K confirmedFirst = confirmed.keySet().iterator().next(); assertEquals(confirmedFirst, ordered.firstKey()); } public void testLastKey() { resetEmpty(); - OrderedMap ordered = getMap(); - try { - ordered.lastKey(); - fail(); - } catch (final NoSuchElementException ex) {} + final OrderedMap ordered1 = getMap(); + Exception exception = assertThrows(NoSuchElementException.class, () -> { + ordered1.lastKey(); + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("Map is empty")); + } resetFull(); - ordered = getMap(); + OrderedMap ordered = getMap(); K confirmedLast = null; for (final Iterator it = confirmed.keySet().iterator(); it.hasNext();) { confirmedLast = it.next(); @@ -140,10 +148,11 @@ public void testNextKey() { assertEquals(null, ordered.nextKey(confirmedLast)); if (!isAllowNullKey()) { - try { - ordered.nextKey(null); - fail(); - } catch (final NullPointerException ex) {} + final OrderedMap ordered1 = getMap(); + Exception exception = assertThrows(NullPointerException.class, () -> { + ordered1.nextKey(null); + }); + assertTrue(exception.getMessage().contains("key")); } else { assertEquals(null, ordered.nextKey(null)); } @@ -175,10 +184,11 @@ public void testPreviousKey() { assertEquals(null, ordered.previousKey(confirmedLast)); if (!isAllowNullKey()) { - try { - ordered.previousKey(null); - fail(); - } catch (final NullPointerException ex) {} + final OrderedMap ordered1 = getMap(); + Exception exception = assertThrows(NullPointerException.class, () -> { + ordered1.previousKey(null); + }); + assertTrue(exception.getMessage().contains("key")); } else { if (!isAllowNullKey()) { assertEquals(null, ordered.previousKey(null)); diff --git a/src/test/java/org/apache/commons/collections4/map/AbstractSortedMapTest.java b/src/test/java/org/apache/commons/collections4/map/AbstractSortedMapTest.java index 108da13378..6a375013d5 100644 --- a/src/test/java/org/apache/commons/collections4/map/AbstractSortedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/AbstractSortedMapTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -238,10 +242,12 @@ public void testHeadMapOutOfRange() { return; } resetEmpty(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { getMap().put(toKey, subSortedValues.get(0)); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("out of range")); + } verify(); } @Override @@ -293,10 +299,12 @@ public void testTailMapOutOfRange() { return; } resetEmpty(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { getMap().put(invalidKey, subSortedValues.get(0)); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("out of range")); + } verify(); } @Override @@ -355,10 +363,12 @@ public void testSubMapOutOfRange() { return; } resetEmpty(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { getMap().put(toKey, subSortedValues.get(0)); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("out of range")); + } verify(); } @Override diff --git a/src/test/java/org/apache/commons/collections4/map/CompositeMapTest.java b/src/test/java/org/apache/commons/collections4/map/CompositeMapTest.java index 967dfd2bd9..72de8f6924 100644 --- a/src/test/java/org/apache/commons/collections4/map/CompositeMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/CompositeMapTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Map; import java.util.HashMap; import java.util.Collection; @@ -78,12 +83,10 @@ public void testAddComposited() { map.addComposited(null); map.addComposited(three); assertTrue(map.containsKey("5")); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { map.addComposited(three); - fail("Expecting IllegalArgumentException."); - } catch (final IllegalArgumentException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Key collision adding Map to CompositeMap")); } @SuppressWarnings("unchecked") diff --git a/src/test/java/org/apache/commons/collections4/map/DefaultedMapTest.java b/src/test/java/org/apache/commons/collections4/map/DefaultedMapTest.java index 01faad37bf..82f925dd6e 100644 --- a/src/test/java/org/apache/commons/collections4/map/DefaultedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/DefaultedMapTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; @@ -54,14 +59,14 @@ public void testMapGet() { final Map map = new DefaultedMap<>((V) "NULL"); assertEquals(0, map.size()); - assertEquals(false, map.containsKey("NotInMap")); + assertFalse(map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); map.put((K) "Key", (V) "Value"); assertEquals(1, map.size()); - assertEquals(true, map.containsKey("Key")); + assertTrue(map.containsKey("Key")); assertEquals("Value", map.get("Key")); - assertEquals(false, map.containsKey("NotInMap")); + assertFalse(map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); } @@ -72,15 +77,15 @@ public void testMapGet2() { assertEquals(0, map.size()); assertEquals(0, base.size()); - assertEquals(false, map.containsKey("NotInMap")); + assertFalse(map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); map.put((K) "Key", (V) "Value"); assertEquals(1, map.size()); assertEquals(1, base.size()); - assertEquals(true, map.containsKey("Key")); + assertTrue(map.containsKey("Key")); assertEquals("Value", map.get("Key")); - assertEquals(false, map.containsKey("NotInMap")); + assertFalse(map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); } @@ -91,15 +96,15 @@ public void testMapGet3() { assertEquals(0, map.size()); assertEquals(0, base.size()); - assertEquals(false, map.containsKey("NotInMap")); + assertFalse(map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); map.put((K) "Key", (V) "Value"); assertEquals(1, map.size()); assertEquals(1, base.size()); - assertEquals(true, map.containsKey("Key")); + assertTrue(map.containsKey("Key")); assertEquals("Value", map.get("Key")); - assertEquals(false, map.containsKey("NotInMap")); + assertFalse(map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); } @@ -115,16 +120,16 @@ public void testMapGet4() { assertEquals(0, map.size()); assertEquals(0, base.size()); - assertEquals(false, map.containsKey("NotInMap")); + assertFalse(map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); assertEquals("NULL_OBJECT", map.get(Integer.valueOf(0))); map.put((K) "Key", (V) "Value"); assertEquals(1, map.size()); assertEquals(1, base.size()); - assertEquals(true, map.containsKey("Key")); + assertTrue(map.containsKey("Key")); assertEquals("Value", map.get("Key")); - assertEquals(false, map.containsKey("NotInMap")); + assertFalse(map.containsKey("NotInMap")); assertEquals("NULL", map.get("NotInMap")); assertEquals("NULL_OBJECT", map.get(Integer.valueOf(0))); } @@ -132,40 +137,30 @@ public void testMapGet4() { public void testFactoryMethods() { final HashMap base = new HashMap<>(); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { DefaultedMap.defaultedMap(null, (V) "DEFAULT_VALUE"); - fail("Expecting NullPointerException"); - } catch (final NullPointerException e) { - // Expected - } + }); + assertTrue(exception.getMessage().contains("map")); - try { + exception = assertThrows(NullPointerException.class, () -> { DefaultedMap.defaultedMap((Map) null, nullFactory); - fail("Expecting NullPointerException"); - } catch (final NullPointerException e) { - // Expected - } + }); + assertTrue(exception.getMessage().contains("map")); - try { + exception = assertThrows(NullPointerException.class, () -> { DefaultedMap.defaultedMap(base, (Factory) null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException e) { - // Expected - } + }); + assertTrue(exception.getMessage().contains("Factory must not be null")); - try { + exception = assertThrows(NullPointerException.class, () -> { DefaultedMap.defaultedMap((Map) null, nullTransformer); - fail("Expecting NullPointerException"); - } catch (final NullPointerException e) { - // Expected - } + }); + assertTrue(exception.getMessage().contains("map")); - try { + exception = assertThrows(NullPointerException.class, () -> { DefaultedMap.defaultedMap(base, (Transformer) null); - fail("Expecting NullPointerException"); - } catch (final NullPointerException e) { - // Expected - } + }); + assertTrue(exception.getMessage().contains("Transformer must not be null")); } @Override diff --git a/src/test/java/org/apache/commons/collections4/map/LRUMapTest.java b/src/test/java/org/apache/commons/collections4/map/LRUMapTest.java index e7ed44c849..f07648ec71 100644 --- a/src/test/java/org/apache/commons/collections4/map/LRUMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/LRUMapTest.java @@ -16,6 +16,14 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -71,47 +79,35 @@ public LRUMap getMap() { //----------------------------------------------------------------------- public void testCtors() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new LRUMap(0); - fail("maxSize must be positive"); - } catch(final IllegalArgumentException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("LRUMap max size must be greater than 0")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { new LRUMap(-1, 12, 0.75f, false); - fail("maxSize must be positive"); - } catch(final IllegalArgumentException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("LRUMap max size must be greater than 0")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { new LRUMap(10, -1); - fail("initialSize must not be negative"); - } catch(final IllegalArgumentException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Initial capacity must be a non negative number")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { new LRUMap(10, 12); - fail("initialSize must not be larger than maxSize"); - } catch(final IllegalArgumentException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("LRUMap initial size must not be greather than max size")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { new LRUMap(10, -1, 0.75f, false); - fail("initialSize must not be negative"); - } catch(final IllegalArgumentException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Initial capacity must be a non negative number")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { new LRUMap(10, 12, 0.75f, false); - fail("initialSize must not be larger than maxSize"); - } catch(final IllegalArgumentException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("LRUMap initial size must not be greather than max size")); } public void testLRU() { @@ -125,17 +121,17 @@ public void testLRU() { final LRUMap map = new LRUMap<>(2); assertEquals(0, map.size()); - assertEquals(false, map.isFull()); + assertFalse(map.isFull()); assertEquals(2, map.maxSize()); map.put(keys[0], values[0]); assertEquals(1, map.size()); - assertEquals(false, map.isFull()); + assertFalse(map.isFull()); assertEquals(2, map.maxSize()); map.put(keys[1], values[1]); assertEquals(2, map.size()); - assertEquals(true, map.isFull()); + assertTrue(map.isFull()); assertEquals(2, map.maxSize()); kit = map.keySet().iterator(); assertSame(keys[0], kit.next()); @@ -146,7 +142,7 @@ public void testLRU() { map.put(keys[2], values[2]); assertEquals(2, map.size()); - assertEquals(true, map.isFull()); + assertTrue(map.isFull()); assertEquals(2, map.maxSize()); kit = map.keySet().iterator(); assertSame(keys[1], kit.next()); @@ -157,7 +153,7 @@ public void testLRU() { map.put(keys[2], values[0]); assertEquals(2, map.size()); - assertEquals(true, map.isFull()); + assertTrue(map.isFull()); assertEquals(2, map.maxSize()); kit = map.keySet().iterator(); assertSame(keys[1], kit.next()); @@ -168,7 +164,7 @@ public void testLRU() { map.put(keys[1], values[3]); assertEquals(2, map.size()); - assertEquals(true, map.isFull()); + assertTrue(map.isFull()); assertEquals(2, map.maxSize()); kit = map.keySet().iterator(); assertSame(keys[2], kit.next()); @@ -342,9 +338,9 @@ public void testRemoveLRU() { assertEquals("a", map.value); assertEquals("C", map.entry.getKey()); // entry is reused assertEquals("c", map.entry.getValue()); // entry is reused - assertEquals(false, map.containsKey("A")); - assertEquals(true, map.containsKey("B")); - assertEquals(true, map.containsKey("C")); + assertFalse(map.containsKey("A")); + assertTrue(map.containsKey("B")); + assertTrue(map.containsKey("C")); } static class MockLRUMapSubclass extends LRUMap { @@ -380,9 +376,9 @@ public void testRemoveLRUBlocksRemove() { map.put((K) "C", (V) "c"); // should remove oldest, which is A=a, but this is blocked assertEquals(3, map.size()); assertEquals(2, map.maxSize()); - assertEquals(true, map.containsKey("A")); - assertEquals(true, map.containsKey("B")); - assertEquals(true, map.containsKey("C")); + assertTrue(map.containsKey("A")); + assertTrue(map.containsKey("B")); + assertTrue(map.containsKey("C")); } @SuppressWarnings("unchecked") @@ -396,9 +392,9 @@ public void testRemoveLRUBlocksRemoveScan() { map.put((K) "C", (V) "c"); // should remove oldest, which is A=a, but this is blocked assertEquals(3, map.size()); assertEquals(2, map.maxSize()); - assertEquals(true, map.containsKey("A")); - assertEquals(true, map.containsKey("B")); - assertEquals(true, map.containsKey("C")); + assertTrue(map.containsKey("A")); + assertTrue(map.containsKey("B")); + assertTrue(map.containsKey("C")); } static class MockLRUMapSubclassBlocksRemove extends LRUMap { @@ -428,9 +424,9 @@ public void testRemoveLRUFirstBlocksRemove() { map.put((K) "C", (V) "c"); // should remove oldest, which is A=a but this is blocked - so advance to B=b assertEquals(2, map.size()); assertEquals(2, map.maxSize()); - assertEquals(true, map.containsKey("A")); - assertEquals(false, map.containsKey("B")); - assertEquals(true, map.containsKey("C")); + assertTrue(map.containsKey("A")); + assertFalse(map.containsKey("B")); + assertTrue(map.containsKey("C")); } static class MockLRUMapSubclassFirstBlocksRemove extends LRUMap { @@ -490,7 +486,7 @@ public void testInternalState_Buckets() { assertEquals(4, map.data.length); assertEquals(3, map.size); - assertEquals(null, map.header.next); + assertNull(map.header.next); assertEquals(one, map.header.after.key); // LRU assertEquals(two, map.header.after.after.key); assertEquals(three, map.header.after.after.after.key); // MRU @@ -502,7 +498,7 @@ public void testInternalState_Buckets() { assertEquals(4, map.data.length); assertEquals(3, map.size); - assertEquals(null, map.header.next); + assertNull(map.header.next); assertEquals(two, map.header.after.key); // LRU assertEquals(three, map.header.after.after.key); assertEquals(four, map.header.after.after.after.key); // MRU @@ -514,7 +510,7 @@ public void testInternalState_Buckets() { assertEquals(4, map.data.length); assertEquals(3, map.size); - assertEquals(null, map.header.next); + assertNull(map.header.next); assertEquals(two, map.header.after.key); // LRU assertEquals(four, map.header.after.after.key); assertEquals(three, map.header.after.after.after.key); // MRU @@ -526,7 +522,7 @@ public void testInternalState_Buckets() { assertEquals(4, map.data.length); assertEquals(3, map.size); - assertEquals(null, map.header.next); + assertNull(map.header.next); assertEquals(four, map.header.after.key); // LRU assertEquals(three, map.header.after.after.key); assertEquals(five, map.header.after.after.after.key); // MRU @@ -539,7 +535,7 @@ public void testInternalState_Buckets() { assertEquals(4, map.data.length); assertEquals(3, map.size); - assertEquals(null, map.header.next); + assertNull(map.header.next); assertEquals(four, map.header.after.key); // LRU assertEquals(three, map.header.after.after.key); assertEquals(five, map.header.after.after.after.key); // MRU @@ -551,7 +547,7 @@ public void testInternalState_Buckets() { assertEquals(4, map.data.length); assertEquals(3, map.size); - assertEquals(null, map.header.next); + assertNull(map.header.next); assertEquals(three, map.header.after.key); // LRU assertEquals(five, map.header.after.after.key); assertEquals(six, map.header.after.after.after.key); // MRU @@ -577,14 +573,14 @@ public void testInternalState_getEntry_int() { assertEquals(one, map.getEntry(0).key); assertEquals(two, map.getEntry(1).key); assertEquals(three, map.getEntry(2).key); - try { + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { map.getEntry(-1); - fail(); - } catch (final IndexOutOfBoundsException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("Index -1 is less than zero")); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { map.getEntry(3); - fail(); - } catch (final IndexOutOfBoundsException ex) {} + }); + assertTrue(exception.getMessage().contains("Index 3 is invalid for size 3")); } public void testSynchronizedRemoveFromMapIterator() throws InterruptedException { @@ -629,7 +625,7 @@ public void run() { } } } catch (final InterruptedException e) { - fail("Unexpected InterruptedException"); + //expected } if (i > 0) { synchronized (counter) { @@ -666,8 +662,7 @@ public void run() { } assertEquals("Exceptions have been thrown: " + exceptions, 0, exceptions.size()); - assertTrue("Each thread should have put at least 1 element into the map, but only " - + counter[0] + " did succeed", counter[0] >= threads.length); + assertTrue(counter[0] >= threads.length); } public void testSynchronizedRemoveFromEntrySet() throws InterruptedException { @@ -749,8 +744,7 @@ public void run() { } assertEquals("Exceptions have been thrown: " + exceptions, 0, exceptions.size()); - assertTrue("Each thread should have put at least 1 element into the map, but only " - + counter[0] + " did succeed", counter[0] >= threads.length); + assertTrue(counter[0] >= threads.length); } public void testSynchronizedRemoveFromKeySet() throws InterruptedException { @@ -832,8 +826,7 @@ public void run() { } assertEquals("Exceptions have been thrown: " + exceptions, 0, exceptions.size()); - assertTrue("Each thread should have put at least 1 element into the map, but only " - + counter[0] + " did succeed", counter[0] >= threads.length); + assertTrue(counter[0] >= threads.length); } public void testSynchronizedRemoveFromValues() throws InterruptedException { @@ -914,8 +907,7 @@ public void run() { } assertEquals("Exceptions have been thrown: " + exceptions, 0, exceptions.size()); - assertTrue("Each thread should have put at least 1 element into the map, but only " - + counter[0] + " did succeed", counter[0] >= threads.length); + assertTrue(counter[0] >= threads.length); } @Override diff --git a/src/test/java/org/apache/commons/collections4/map/LazySortedMapTest.java b/src/test/java/org/apache/commons/collections4/map/LazySortedMapTest.java index 29f3e04621..0044c80e53 100644 --- a/src/test/java/org/apache/commons/collections4/map/LazySortedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/LazySortedMapTest.java @@ -17,6 +17,10 @@ package org.apache.commons.collections4.map; import static org.apache.commons.collections4.map.LazySortedMap.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Comparator; import java.util.Map; @@ -81,7 +85,7 @@ public void mapGet() { map = lazySortedMap(new TreeMap(), FactoryUtils.nullFactory()); final Number o = map.get(5); - assertEquals(null, o); + assertNull(o); assertEquals(1, map.size()); } @@ -102,8 +106,7 @@ public void testSortOrder() { "B", map.subMap("A", "C").lastKey()); final Comparator c = map.comparator(); - assertTrue("natural order, so comparator should be null", - c == null); + assertNull(c); } public void testReverseSortOrder() { @@ -121,26 +124,21 @@ public void testReverseSortOrder() { "B", map.subMap("C", "A").lastKey()); final Comparator c = map.comparator(); - assertTrue("natural order, so comparator should be null", - c == reverseStringComparator); + assertTrue(c == reverseStringComparator); } public void testTransformerDecorate() { final Transformer transformer = TransformerUtils.asTransformer(oneFactory); SortedMap map = lazySortedMap(new TreeMap(), transformer); assertTrue(map instanceof LazySortedMap); - try { - map = lazySortedMap(new TreeMap(), (Transformer) null); - fail("Expecting NullPointerException for null transformer"); - } catch (final NullPointerException e) { - // expected - } - try { - map = lazySortedMap((SortedMap) null, transformer); - fail("Expecting NullPointerException for null map"); - } catch (final NullPointerException e) { - // expected - } + Exception exception = assertThrows(NullPointerException.class, () -> { + lazySortedMap(new TreeMap(), (Transformer) null); + }); + assertTrue(exception.getMessage().contains("factory")); + exception = assertThrows(NullPointerException.class, () -> { + lazySortedMap((SortedMap) null, transformer); + }); + assertTrue(exception.getMessage().contains("map")); } @Override diff --git a/src/test/java/org/apache/commons/collections4/map/ListOrderedMapTest.java b/src/test/java/org/apache/commons/collections4/map/ListOrderedMapTest.java index b0238c6e69..287f957193 100644 --- a/src/test/java/org/apache/commons/collections4/map/ListOrderedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/ListOrderedMapTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -181,24 +186,25 @@ public void testRemoveByIndex() { final Object value = lom.get(key); assertEquals(value, lom.remove(i)); list.remove(i); - assertEquals(false, lom.containsKey(key)); + assertFalse(lom.containsKey(key)); } } @SuppressWarnings("unchecked") public void testPut_intObjectObject() { resetEmpty(); - ListOrderedMap lom = getMap(); + final ListOrderedMap lom1 = getMap(); - try { - lom.put(1, (K) "testInsert1", (V) "testInsert1v"); - fail("should not be able to insert at pos 1 in empty Map"); - } catch (final IndexOutOfBoundsException ex) {} - try { - lom.put(-1, (K) "testInsert-1", (V) "testInsert-1v"); - fail("should not be able to insert at pos -1 in empty Map"); - } catch (final IndexOutOfBoundsException ex) {} + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + lom1.put(1, (K) "testInsert1", (V) "testInsert1v"); + }); + assertTrue(exception.getMessage().contains("Index: 1, Size: 0")); + exception = assertThrows(IndexOutOfBoundsException.class, () -> { + lom1.put(-1, (K) "testInsert-1", (V) "testInsert-1v"); + }); + assertTrue(exception.getMessage().contains("Index: -1, Size: 0")); + ListOrderedMap lom = getMap(); // put where key doesn't exist lom.put(0, (K) "testInsert1", (V) "testInsert1v"); assertEquals("testInsert1v", lom.getValue(0)); diff --git a/src/test/java/org/apache/commons/collections4/map/MultiKeyMapTest.java b/src/test/java/org/apache/commons/collections4/map/MultiKeyMapTest.java index dbac088a30..fedcd31c03 100644 --- a/src/test/java/org/apache/commons/collections4/map/MultiKeyMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/MultiKeyMapTest.java @@ -16,6 +16,13 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Map; import junit.framework.Test; @@ -117,22 +124,22 @@ public boolean isAllowNullKey() { @SuppressWarnings("unchecked") public void testNullHandling() { resetFull(); - assertEquals(null, map.get(null)); - assertEquals(false, map.containsKey(null)); - assertEquals(false, map.containsValue(null)); - assertEquals(null, map.remove(null)); - assertEquals(false, map.entrySet().contains(null)); - assertEquals(false, map.keySet().contains(null)); - assertEquals(false, map.values().contains(null)); - try { + assertNull(map.get(null)); + assertFalse(map.containsKey(null)); + assertFalse(map.containsValue(null)); + assertNull(map.remove(null)); + assertFalse(map.entrySet().contains(null)); + assertFalse(map.keySet().contains(null)); + assertFalse(map.values().contains(null)); + Exception exception = assertThrows(NullPointerException.class, () -> { map.put(null, null); - fail(); - } catch (final NullPointerException ex) {} - assertEquals(null, map.put(new MultiKey(null, null), null)); - try { + }); + assertTrue(exception.getMessage().contains("key")); + assertNull(map.put(new MultiKey(null, null), null)); + exception = assertThrows(NullPointerException.class, () -> { map.put(null, (V) new Object()); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("key")); } //----------------------------------------------------------------------- @@ -149,39 +156,39 @@ public void testMultiKeyGet() { switch (key.size()) { case 2: assertEquals(value, multimap.get(key.getKey(0), key.getKey(1))); - assertEquals(null, multimap.get(null, key.getKey(1))); - assertEquals(null, multimap.get(key.getKey(0), null)); - assertEquals(null, multimap.get(null, null)); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null)); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null, null)); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null, null, null)); + assertNull(multimap.get(null, key.getKey(1))); + assertNull(multimap.get(key.getKey(0), null)); + assertNull(multimap.get(null, null)); + assertNull(multimap.get(key.getKey(0), key.getKey(1), null)); + assertNull(multimap.get(key.getKey(0), key.getKey(1), null, null)); + assertNull(multimap.get(key.getKey(0), key.getKey(1), null, null, null)); break; case 3: assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2))); - assertEquals(null, multimap.get(null, key.getKey(1), key.getKey(2))); - assertEquals(null, multimap.get(key.getKey(0), null, key.getKey(2))); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null)); - assertEquals(null, multimap.get(null, null, null)); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null)); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null, null)); + assertNull(multimap.get(null, key.getKey(1), key.getKey(2))); + assertNull(multimap.get(key.getKey(0), null, key.getKey(2))); + assertNull(multimap.get(key.getKey(0), key.getKey(1), null)); + assertNull(multimap.get(null, null, null)); + assertNull(multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null)); + assertNull(multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null, null)); break; case 4: assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); - assertEquals(null, multimap.get(null, key.getKey(1), key.getKey(2), key.getKey(3))); - assertEquals(null, multimap.get(key.getKey(0), null, key.getKey(2), key.getKey(3))); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null, key.getKey(3))); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null)); - assertEquals(null, multimap.get(null, null, null, null)); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); + assertNull(multimap.get(null, key.getKey(1), key.getKey(2), key.getKey(3))); + assertNull(multimap.get(key.getKey(0), null, key.getKey(2), key.getKey(3))); + assertNull(multimap.get(key.getKey(0), key.getKey(1), null, key.getKey(3))); + assertNull(multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null)); + assertNull(multimap.get(null, null, null, null)); + assertNull(multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); break; case 5: assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(null, multimap.get(null, key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(null, multimap.get(key.getKey(0), null, key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), null, key.getKey(3), key.getKey(4))); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null, key.getKey(4))); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); - assertEquals(null, multimap.get(null, null, null, null, null)); + assertNull(multimap.get(null, key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); + assertNull(multimap.get(key.getKey(0), null, key.getKey(2), key.getKey(3), key.getKey(4))); + assertNull(multimap.get(key.getKey(0), key.getKey(1), null, key.getKey(3), key.getKey(4))); + assertNull(multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), null, key.getKey(4))); + assertNull(multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); + assertNull(multimap.get(null, null, null, null, null)); break; default: fail("Invalid key size"); @@ -197,40 +204,40 @@ public void testMultiKeyContainsKey() { for (final MultiKey key : keys) { switch (key.size()) { case 2: - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); - assertEquals(false, multimap.containsKey(null, key.getKey(1))); - assertEquals(false, multimap.containsKey(key.getKey(0), null)); - assertEquals(false, multimap.containsKey(null, null)); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null)); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null, null)); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null, null, null)); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1))); + assertFalse(multimap.containsKey(null, key.getKey(1))); + assertFalse(multimap.containsKey(key.getKey(0), null)); + assertFalse(multimap.containsKey(null, null)); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), null)); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), null, null)); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), null, null, null)); break; case 3: - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); - assertEquals(false, multimap.containsKey(null, key.getKey(1), key.getKey(2))); - assertEquals(false, multimap.containsKey(key.getKey(0), null, key.getKey(2))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null)); - assertEquals(false, multimap.containsKey(null, null, null)); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null)); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null, null)); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); + assertFalse(multimap.containsKey(null, key.getKey(1), key.getKey(2))); + assertFalse(multimap.containsKey(key.getKey(0), null, key.getKey(2))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), null)); + assertFalse(multimap.containsKey(null, null, null)); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null)); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null, null)); break; case 4: - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); - assertEquals(false, multimap.containsKey(null, key.getKey(1), key.getKey(2), key.getKey(3))); - assertEquals(false, multimap.containsKey(key.getKey(0), null, key.getKey(2), key.getKey(3))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null, key.getKey(3))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null)); - assertEquals(false, multimap.containsKey(null, null, null, null)); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); + assertFalse(multimap.containsKey(null, key.getKey(1), key.getKey(2), key.getKey(3))); + assertFalse(multimap.containsKey(key.getKey(0), null, key.getKey(2), key.getKey(3))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), null, key.getKey(3))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null)); + assertFalse(multimap.containsKey(null, null, null, null)); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); break; case 5: - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(false, multimap.containsKey(null, key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(false, multimap.containsKey(key.getKey(0), null, key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), null, key.getKey(3), key.getKey(4))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null, key.getKey(4))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); - assertEquals(false, multimap.containsKey(null, null, null, null, null)); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); + assertFalse(multimap.containsKey(null, key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); + assertFalse(multimap.containsKey(key.getKey(0), null, key.getKey(2), key.getKey(3), key.getKey(4))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), null, key.getKey(3), key.getKey(4))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), null, key.getKey(4))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); + assertFalse(multimap.containsKey(null, null, null, null, null)); break; default: fail("Invalid key size"); @@ -250,48 +257,48 @@ public void testMultiKeyPut() { switch (key.size()) { case 2: - assertEquals(null, multimap.put(key.getKey(0), key.getKey(1), value)); + assertNull(multimap.put(key.getKey(0), key.getKey(1), value)); assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1))); - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); - assertEquals(true, multimap.containsKey(new MultiKey<>(key.getKey(0), key.getKey(1)))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1))); + assertTrue(multimap.containsKey(new MultiKey<>(key.getKey(0), key.getKey(1)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), null)); assertEquals(1, multimap.size()); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1))); - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); + assertNull(multimap.get(key.getKey(0), key.getKey(1))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1))); break; case 3: - assertEquals(null, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), value)); + assertNull(multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), value)); assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2))); - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); - assertEquals(true, multimap.containsKey(new MultiKey<>(key.getKey(0), key.getKey(1), key.getKey(2)))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); + assertTrue(multimap.containsKey(new MultiKey<>(key.getKey(0), key.getKey(1), key.getKey(2)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), null)); assertEquals(1, multimap.size()); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2))); - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); + assertNull(multimap.get(key.getKey(0), key.getKey(1), key.getKey(2))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); break; case 4: - assertEquals(null, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), value)); + assertNull(multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), value)); assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); - assertEquals(true, multimap.containsKey(new MultiKey<>(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3)))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); + assertTrue(multimap.containsKey(new MultiKey<>(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), null)); assertEquals(1, multimap.size()); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); + assertNull(multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); break; case 5: - assertEquals(null, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4), value)); + assertNull(multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4), value)); assertEquals(1, multimap.size()); assertEquals(value, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(true, multimap.containsKey(new MultiKey<>(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4)))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); + assertTrue(multimap.containsKey(new MultiKey<>(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4)))); assertEquals(value, multimap.put(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4), null)); assertEquals(1, multimap.size()); - assertEquals(null, multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); + assertNull(multimap.get(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); break; default: fail("Invalid key size"); @@ -329,36 +336,36 @@ public void testMultiKeyRemove() { switch (key.size()) { case 2: - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1))); assertEquals(value, multimap.removeMultiKey(key.getKey(0), key.getKey(1))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1))); assertEquals(size - 1, multimap.size()); - assertEquals(null, multimap.removeMultiKey(key.getKey(0), key.getKey(1))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1))); + assertNull(multimap.removeMultiKey(key.getKey(0), key.getKey(1))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1))); break; case 3: - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(value, multimap.removeMultiKey(key.getKey(0), key.getKey(1), key.getKey(2))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); assertEquals(size - 1, multimap.size()); - assertEquals(null, multimap.removeMultiKey(key.getKey(0), key.getKey(1), key.getKey(2))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); + assertNull(multimap.removeMultiKey(key.getKey(0), key.getKey(1), key.getKey(2))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2))); break; case 4: - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(value, multimap.removeMultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); assertEquals(size - 1, multimap.size()); - assertEquals(null, multimap.removeMultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); + assertNull(multimap.removeMultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3))); break; case 5: - assertEquals(true, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); + assertTrue(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(value, multimap.removeMultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); assertEquals(size - 1, multimap.size()); - assertEquals(null, multimap.removeMultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); - assertEquals(false, multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); + assertNull(multimap.removeMultiKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); + assertFalse(multimap.containsKey(key.getKey(0), key.getKey(1), key.getKey(2), key.getKey(3), key.getKey(4))); break; default: fail("Invalid key size"); @@ -375,7 +382,7 @@ public void testMultiKeyRemoveAll1() { assertEquals(8, multimap.size()); for (final MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { final MultiKey key = it.next(); - assertEquals(false, I1.equals(key.getKey(0))); + assertFalse(I1.equals(key.getKey(0))); } } @@ -388,7 +395,7 @@ public void testMultiKeyRemoveAll2() { assertEquals(9, multimap.size()); for (final MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { final MultiKey key = it.next(); - assertEquals(false, I2.equals(key.getKey(0)) && I3.equals(key.getKey(1))); + assertFalse(I2.equals(key.getKey(0)) && I3.equals(key.getKey(1))); } } @@ -401,7 +408,7 @@ public void testMultiKeyRemoveAll3() { assertEquals(9, multimap.size()); for (final MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { final MultiKey key = it.next(); - assertEquals(false, I1.equals(key.getKey(0)) && I1.equals(key.getKey(1)) && I2.equals(key.getKey(2))); + assertFalse(I1.equals(key.getKey(0)) && I1.equals(key.getKey(1)) && I2.equals(key.getKey(2))); } } @@ -414,7 +421,7 @@ public void testMultiKeyRemoveAll4() { assertEquals(10, multimap.size()); for (final MapIterator, V> it = multimap.mapIterator(); it.hasNext();) { final MultiKey key = it.next(); - assertEquals(false, I1.equals(key.getKey(0)) && I1.equals(key.getKey(1)) && I2.equals(key.getKey(2)) && key.size() >= 4 && I3.equals(key.getKey(3))); + assertFalse(I1.equals(key.getKey(0)) && I1.equals(key.getKey(1)) && I2.equals(key.getKey(2)) && key.size() >= 4 && I3.equals(key.getKey(3))); } } @@ -437,19 +444,19 @@ public void testLRUMultiKeyMap() { assertEquals(2, map.size()); map.put((K) I1, (K) I4, (V) "1-4"); assertEquals(2, map.size()); - assertEquals(true, map.containsKey(I1, I3)); - assertEquals(true, map.containsKey(I1, I4)); - assertEquals(false, map.containsKey(I1, I2)); + assertTrue(map.containsKey(I1, I3)); + assertTrue(map.containsKey(I1, I4)); + assertFalse(map.containsKey(I1, I2)); final MultiKeyMap cloned = map.clone(); assertEquals(2, map.size()); - assertEquals(true, cloned.containsKey(I1, I3)); - assertEquals(true, cloned.containsKey(I1, I4)); - assertEquals(false, cloned.containsKey(I1, I2)); + assertTrue(cloned.containsKey(I1, I3)); + assertTrue(cloned.containsKey(I1, I4)); + assertFalse(cloned.containsKey(I1, I2)); cloned.put((K) I1, (K) I5, (V) "1-5"); assertEquals(2, cloned.size()); - assertEquals(true, cloned.containsKey(I1, I4)); - assertEquals(true, cloned.containsKey(I1, I5)); + assertTrue(cloned.containsKey(I1, I4)); + assertTrue(cloned.containsKey(I1, I5)); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/map/MultiValueMapTest.java b/src/test/java/org/apache/commons/collections4/map/MultiValueMapTest.java index 5c4f7f69d1..4c955113a5 100644 --- a/src/test/java/org/apache/commons/collections4/map/MultiValueMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/MultiValueMapTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -264,19 +270,19 @@ public void testIterator_Key() { assertEquals(false, map.iterator("A").hasNext()); map.put((K) "A", "AA"); final Iterator it = map.iterator("A"); - assertEquals(true, it.hasNext()); + assertTrue(it.hasNext()); it.next(); - assertEquals(false, it.hasNext()); + assertFalse(it.hasNext()); } @SuppressWarnings("unchecked") public void testContainsValue_Key() { final MultiValueMap map = new MultiValueMap<>(); - assertEquals(false, map.containsValue("A", "AA")); - assertEquals(false, map.containsValue("B", "BB")); + assertFalse(map.containsValue("A", "AA")); + assertFalse(map.containsValue("B", "BB")); map.put((K) "A", "AA"); - assertEquals(true, map.containsValue("A", "AA")); - assertEquals(false, map.containsValue("A", "AB")); + assertTrue(map.containsValue("A", "AA")); + assertFalse(map.containsValue("A", "AB")); } @SuppressWarnings("unchecked") @@ -296,7 +302,7 @@ public void testPutWithSet() { final MultiValueMap test = MultiValueMap.multiValueMap(new HashMap(), HashSet.class); assertEquals("a", test.put((K) "A", "a")); assertEquals("b", test.put((K) "A", "b")); - assertEquals(null, test.put((K) "A", "a")); + assertNull(test.put((K) "A", "a")); assertEquals(1, test.size()); assertEquals(2, test.size("A")); assertEquals(2, test.totalSize()); @@ -317,10 +323,10 @@ public void testPutAll_Map1() { assertEquals(4, test.totalSize()); assertEquals(1, test.getCollection("keyA").size()); assertEquals(3, test.getCollection("key").size()); - assertEquals(true, test.containsValue("objectA")); - assertEquals(true, test.containsValue("object0")); - assertEquals(true, test.containsValue("object1")); - assertEquals(true, test.containsValue("object2")); + assertTrue(test.containsValue("objectA")); + assertTrue(test.containsValue("object0")); + assertTrue(test.containsValue("object1")); + assertTrue(test.containsValue("object2")); } @SuppressWarnings("unchecked") @@ -339,10 +345,10 @@ public void testPutAll_Map2() { assertEquals(1, test.getCollection("keyA").size()); assertEquals(2, test.getCollection("keyX").size()); assertEquals(1, test.getCollection("keyY").size()); - assertEquals(true, test.containsValue("objectA")); - assertEquals(true, test.containsValue("object0")); - assertEquals(true, test.containsValue("object1")); - assertEquals(true, test.containsValue("object2")); + assertTrue(test.containsValue("objectA")); + assertTrue(test.containsValue("object0")); + assertTrue(test.containsValue("object1")); + assertTrue(test.containsValue("object2")); } @SuppressWarnings("unchecked") @@ -350,31 +356,31 @@ public void testPutAll_KeyCollection() { final MultiValueMap map = new MultiValueMap<>(); Collection coll = (Collection) Arrays.asList("X", "Y", "Z"); - assertEquals(true, map.putAll((K) "A", coll)); + assertTrue(map.putAll((K) "A", coll)); assertEquals(3, map.size("A")); - assertEquals(true, map.containsValue("A", "X")); - assertEquals(true, map.containsValue("A", "Y")); - assertEquals(true, map.containsValue("A", "Z")); + assertTrue(map.containsValue("A", "X")); + assertTrue(map.containsValue("A", "Y")); + assertTrue(map.containsValue("A", "Z")); - assertEquals(false, map.putAll((K) "A", null)); + assertFalse(map.putAll((K) "A", null)); assertEquals(3, map.size("A")); - assertEquals(true, map.containsValue("A", "X")); - assertEquals(true, map.containsValue("A", "Y")); - assertEquals(true, map.containsValue("A", "Z")); + assertTrue(map.containsValue("A", "X")); + assertTrue(map.containsValue("A", "Y")); + assertTrue(map.containsValue("A", "Z")); - assertEquals(false, map.putAll((K) "A", new ArrayList())); + assertFalse(map.putAll((K) "A", new ArrayList())); assertEquals(3, map.size("A")); - assertEquals(true, map.containsValue("A", "X")); - assertEquals(true, map.containsValue("A", "Y")); - assertEquals(true, map.containsValue("A", "Z")); + assertTrue(map.containsValue("A", "X")); + assertTrue(map.containsValue("A", "Y")); + assertTrue(map.containsValue("A", "Z")); coll = (Collection) Arrays.asList("M"); - assertEquals(true, map.putAll((K) "A", coll)); + assertTrue(map.putAll((K) "A", coll)); assertEquals(4, map.size("A")); - assertEquals(true, map.containsValue("A", "X")); - assertEquals(true, map.containsValue("A", "Y")); - assertEquals(true, map.containsValue("A", "Z")); - assertEquals(true, map.containsValue("A", "M")); + assertTrue(map.containsValue("A", "X")); + assertTrue(map.containsValue("A", "Y")); + assertTrue(map.containsValue("A", "Z")); + assertTrue(map.containsValue("A", "M")); } @SuppressWarnings("unchecked") @@ -383,11 +389,11 @@ public void testRemove_KeyItem() { map.put((K) "A", "AA"); map.put((K) "A", "AB"); map.put((K) "A", "AC"); - assertEquals(false, map.removeMapping("C", "CA")); - assertEquals(false, map.removeMapping("A", "AD")); - assertEquals(true, map.removeMapping("A", "AC")); - assertEquals(true, map.removeMapping("A", "AB")); - assertEquals(true, map.removeMapping("A", "AA")); + assertFalse(map.removeMapping("C", "CA")); + assertFalse(map.removeMapping("A", "AD")); + assertTrue(map.removeMapping("A", "AC")); + assertTrue(map.removeMapping("A", "AB")); + assertTrue(map.removeMapping("A", "AA")); assertEquals(new MultiValueMap(), map); } @@ -398,13 +404,11 @@ public void testUnsafeDeSerialization() throws Exception { assertEquals(map1, result); final MultiValueMap map2 = MultiValueMap.multiValueMap(new HashMap(), (Class) String.class); - bytes = serialize(map2); - try { - result = deserialize(bytes); - fail("unsafe clazz accepted when de-serializing MultiValueMap"); - } catch (final UnsupportedOperationException ex) { - // expected - } + final byte[] bytes2 = serialize(map2); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + deserialize(bytes2); + }); + assertNull(exception.getMessage()); } private byte[] serialize(final Object object) throws IOException { @@ -462,7 +466,7 @@ public void testFullMapCompatibility() throws Exception { final Map map2 = (Map) readExternalFormFromDisk(getCanonicalFullCollectionName(map)); assertEquals("Map is the right size", map.size(), map2.size()); for (final Object key : map.keySet()) { - assertEquals( "Map had inequal elements", map.get(key), map2.get(key) ); + assertEquals("Map had inequal elements", map.get(key), map2.get(key) ); map2.remove(key); } assertEquals("Map had extra values", 0, map2.size()); diff --git a/src/test/java/org/apache/commons/collections4/map/PassiveExpiringMapTest.java b/src/test/java/org/apache/commons/collections4/map/PassiveExpiringMapTest.java index 4edaf51254..d4384956c4 100644 --- a/src/test/java/org/apache/commons/collections4/map/PassiveExpiringMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/PassiveExpiringMapTest.java @@ -16,6 +16,13 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -102,29 +109,23 @@ private Map makeTestMap() { } public void testConstructors() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { final Map map = null; new PassiveExpiringMap<>(map); - fail("constructor - exception should have been thrown."); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("map")); - try { + exception = assertThrows(NullPointerException.class, () -> { final ExpirationPolicy policy = null; new PassiveExpiringMap<>(policy); - fail("constructor - exception should have been thrown."); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("expiringPolicy")); - try { + exception = assertThrows(NullPointerException.class, () -> { final TimeUnit unit = null; new PassiveExpiringMap(10L, unit); - fail("constructor - exception should have been thrown."); - } catch (final NullPointerException ex) { - // success - } + }); + assertTrue(exception.getMessage().contains("timeUnit")); } public void testContainsKey() { @@ -251,8 +252,8 @@ private void validateExpiration(final Map map, final long timeou try { Thread.sleep(2 * timeout); - } catch (final InterruptedException e) { - fail(); + } catch (InterruptedException ex) { + //expected } assertNull(map.get("a")); diff --git a/src/test/java/org/apache/commons/collections4/map/PredicatedMapTest.java b/src/test/java/org/apache/commons/collections4/map/PredicatedMapTest.java index b9f52b299d..9edde3b52e 100644 --- a/src/test/java/org/apache/commons/collections4/map/PredicatedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/PredicatedMapTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -59,31 +62,25 @@ public IterableMap makeTestMap() { @SuppressWarnings("unchecked") public void testEntrySet() { Map map = makeTestMap(); - assertTrue("returned entryset should not be null", - map.entrySet() != null); + assertTrue(map.entrySet() != null); map = decorateMap(new HashMap(), null, null); map.put((K) "oneKey", (V) "oneValue"); - assertTrue("returned entryset should contain one entry", - map.entrySet().size() == 1); + assertTrue(map.entrySet().size() == 1); map = decorateMap(map, null, null); } @SuppressWarnings("unchecked") public void testPut() { final Map map = makeTestMap(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { map.put((K) "Hi", (V) Integer.valueOf(3)); - fail("Illegal value should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add value - Predicate rejected it")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { map.put((K) Integer.valueOf(3), (V) "Hi"); - fail("Illegal key should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add key - Predicate rejected it")); assertTrue(!map.containsKey(Integer.valueOf(3))); assertTrue(!map.containsValue(Integer.valueOf(3))); @@ -94,26 +91,22 @@ public void testPut() { map2.put((K) "C", (V) "c"); map2.put((K) "c", (V) Integer.valueOf(3)); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { map.putAll(map2); - fail("Illegal value should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add value - Predicate rejected it")); map.put((K) "E", (V) "e"); - Iterator> iterator = map.entrySet().iterator(); - try { + final Iterator> iterator = map.entrySet().iterator(); + exception = assertThrows(IllegalArgumentException.class, () -> { final Map.Entry entry = iterator.next(); entry.setValue((V) Integer.valueOf(3)); - fail("Illegal value should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot set value - Predicate rejected it")); map.put((K) "F", (V) "f"); - iterator = map.entrySet().iterator(); - final Map.Entry entry = iterator.next(); + Iterator> iterator2 = map.entrySet().iterator(); + final Map.Entry entry = iterator2.next(); entry.setValue((V) "x"); } diff --git a/src/test/java/org/apache/commons/collections4/map/PredicatedSortedMapTest.java b/src/test/java/org/apache/commons/collections4/map/PredicatedSortedMapTest.java index 47ff45684a..902ad33d70 100644 --- a/src/test/java/org/apache/commons/collections4/map/PredicatedSortedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/PredicatedSortedMapTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; @@ -87,31 +92,25 @@ public boolean isAllowNullKey() { @SuppressWarnings("unchecked") public void testEntrySet() { SortedMap map = makeTestMap(); - assertTrue("returned entryset should not be null", - map.entrySet() != null); + assertTrue(map.entrySet() != null); map = decorateMap(new TreeMap(), null, null); map.put((K) "oneKey", (V) "oneValue"); - assertTrue("returned entryset should contain one entry", - map.entrySet().size() == 1); + assertTrue(map.entrySet().size() == 1); map = decorateMap(map, null, null); } @SuppressWarnings("unchecked") public void testPut() { final Map map = makeTestMap(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { map.put((K) "Hi", (V) Integer.valueOf(3)); - fail("Illegal value should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add value - Predicate rejected it")); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { map.put((K) Integer.valueOf(3), (V) "Hi"); - fail("Illegal key should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add key - Predicate rejected it")); assertTrue(!map.containsKey(Integer.valueOf(3))); assertTrue(!map.containsValue(Integer.valueOf(3))); @@ -122,26 +121,22 @@ public void testPut() { map2.put((K) "C", (V) "c"); map2.put((K) "c", (V) Integer.valueOf(3)); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { map.putAll(map2); - fail("Illegal value should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add value - Predicate rejected it")); map.put((K) "E", (V) "e"); - Iterator> iterator = map.entrySet().iterator(); - try { + final Iterator> iterator = map.entrySet().iterator(); + exception = assertThrows(IllegalArgumentException.class, () -> { final Map.Entry entry = iterator.next(); entry.setValue((V) Integer.valueOf(3)); - fail("Illegal value should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot set value - Predicate rejected it")); map.put((K) "F", (V) "f"); - iterator = map.entrySet().iterator(); - final Map.Entry entry = iterator.next(); + Iterator> iterator2 = map.entrySet().iterator(); + final Map.Entry entry = iterator2.next(); entry.setValue((V) "x"); } @@ -152,19 +147,16 @@ public void testSortOrder() { final SortedMap map = makeTestMap(); map.put((K) "A", (V) "a"); map.put((K) "B", (V) "b"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { map.put(null, (V) "c"); - fail("Null key should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add key - Predicate rejected it")); + map.put((K) "C", (V) "c"); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { map.put((K) "D", null); - fail("Null value should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add value - Predicate rejected it")); assertEquals("First key should be A", "A", map.firstKey()); assertEquals("Last key should be C", "C", map.lastKey()); assertEquals("First key in tail map should be B", @@ -175,8 +167,7 @@ public void testSortOrder() { "B", map.subMap((K) "A", (K) "C").lastKey()); final Comparator c = map.comparator(); - assertTrue("natural order, so comparator should be null", - c == null); + assertNull(c); } @SuppressWarnings("unchecked") @@ -184,19 +175,15 @@ public void testReverseSortOrder() { final SortedMap map = makeTestMapWithComparator(); map.put((K) "A", (V) "a"); map.put((K) "B", (V) "b"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { map.put(null, (V) "c"); - fail("Null key should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add key - Predicate rejected it")); map.put((K) "C", (V) "c"); - try { + exception = assertThrows(IllegalArgumentException.class, () -> { map.put((K) "D", null); - fail("Null value should raise IllegalArgument"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Cannot add value - Predicate rejected it")); assertEquals("Last key should be A", "A", map.lastKey()); assertEquals("First key should be C", "C", map.firstKey()); assertEquals("First key in tail map should be B", @@ -207,8 +194,7 @@ public void testReverseSortOrder() { "B", map.subMap((K) "C", (K) "A").lastKey()); final Comparator c = map.comparator(); - assertTrue("reverse order, so comparator should be reverseStringComparator", - c == reverseStringComparator); + assertTrue(c == reverseStringComparator); } @Override diff --git a/src/test/java/org/apache/commons/collections4/map/ReferenceIdentityMapTest.java b/src/test/java/org/apache/commons/collections4/map/ReferenceIdentityMapTest.java index 1ccc8ec979..b45fd3609e 100644 --- a/src/test/java/org/apache/commons/collections4/map/ReferenceIdentityMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/ReferenceIdentityMapTest.java @@ -16,6 +16,13 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.lang.ref.WeakReference; import java.util.Iterator; import java.util.Map; @@ -93,29 +100,29 @@ public void testBasics() { map.put((K) I1A, (V) I2A); assertEquals(1, map.size()); assertSame(I2A, map.get(I1A)); - assertSame(null, map.get(I1B)); - assertEquals(true, map.containsKey(I1A)); - assertEquals(false, map.containsKey(I1B)); - assertEquals(true, map.containsValue(I2A)); - assertEquals(false, map.containsValue(I2B)); + assertNull(map.get(I1B)); + assertTrue(map.containsKey(I1A)); + assertFalse(map.containsKey(I1B)); + assertTrue(map.containsValue(I2A)); + assertFalse(map.containsValue(I2B)); map.put((K) I1A, (V) I2B); assertEquals(1, map.size()); assertSame(I2B, map.get(I1A)); - assertSame(null, map.get(I1B)); - assertEquals(true, map.containsKey(I1A)); - assertEquals(false, map.containsKey(I1B)); - assertEquals(false, map.containsValue(I2A)); - assertEquals(true, map.containsValue(I2B)); + assertNull(map.get(I1B)); + assertTrue(map.containsKey(I1A)); + assertFalse(map.containsKey(I1B)); + assertFalse(map.containsValue(I2A)); + assertTrue(map.containsValue(I2B)); map.put((K) I1B, (V) I2B); assertEquals(2, map.size()); assertSame(I2B, map.get(I1A)); assertSame(I2B, map.get(I1B)); - assertEquals(true, map.containsKey(I1A)); - assertEquals(true, map.containsKey(I1B)); - assertEquals(false, map.containsValue(I2A)); - assertEquals(true, map.containsValue(I2B)); + assertTrue(map.containsKey(I1A)); + assertTrue(map.containsKey(I1B)); + assertFalse(map.containsValue(I2A)); + assertTrue(map.containsValue(I2B)); } //----------------------------------------------------------------------- @@ -131,34 +138,34 @@ public void testHashEntry() { final Map.Entry entry2 = it.next(); final Map.Entry entry3 = it.next(); - assertEquals(true, entry1.equals(entry2)); - assertEquals(true, entry2.equals(entry1)); - assertEquals(false, entry1.equals(entry3)); + assertTrue(entry1.equals(entry2)); + assertTrue(entry2.equals(entry1)); + assertFalse(entry1.equals(entry3)); } //----------------------------------------------------------------------- @SuppressWarnings("unchecked") public void testNullHandling() { resetFull(); - assertEquals(null, getMap().get(null)); - assertEquals(false, getMap().containsKey(null)); - assertEquals(false, getMap().containsValue(null)); - assertEquals(null, getMap().remove(null)); - assertEquals(false, getMap().entrySet().contains(null)); - assertEquals(false, getMap().keySet().contains(null)); - assertEquals(false, getMap().values().contains(null)); - try { + assertNull(getMap().get(null)); + assertFalse(getMap().containsKey(null)); + assertFalse(getMap().containsValue(null)); + assertNull(getMap().remove(null)); + assertFalse(getMap().entrySet().contains(null)); + assertFalse(getMap().keySet().contains(null)); + assertFalse(getMap().values().contains(null)); + Exception exception = assertThrows(NullPointerException.class, () -> { getMap().put(null, null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("key")); + exception = assertThrows(NullPointerException.class, () -> { getMap().put((K) new Object(), null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("value")); + exception = assertThrows(NullPointerException.class, () -> { getMap().put(null, (V) new Object()); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("key")); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/map/ReferenceMapTest.java b/src/test/java/org/apache/commons/collections4/map/ReferenceMapTest.java index eff9bc46ba..8085555450 100644 --- a/src/test/java/org/apache/commons/collections4/map/ReferenceMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/ReferenceMapTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -84,25 +90,25 @@ public String getCompatibilityVersion() { @SuppressWarnings("unchecked") public void testNullHandling() { resetFull(); - assertEquals(null, map.get(null)); - assertEquals(false, map.containsKey(null)); - assertEquals(false, map.containsValue(null)); - assertEquals(null, map.remove(null)); - assertEquals(false, map.entrySet().contains(null)); - assertEquals(false, map.keySet().contains(null)); - assertEquals(false, map.values().contains(null)); - try { + assertNull(map.get(null)); + assertFalse(map.containsKey(null)); + assertFalse(map.containsValue(null)); + assertNull(map.remove(null)); + assertFalse(map.entrySet().contains(null)); + assertFalse(map.keySet().contains(null)); + assertFalse(map.values().contains(null)); + Exception exception = assertThrows(NullPointerException.class, () -> { map.put(null, null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("key")); + exception = assertThrows(NullPointerException.class, () -> { map.put((K) new Object(), null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("value")); + exception = assertThrows(NullPointerException.class, () -> { map.put(null, (V) new Object()); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("key")); } //----------------------------------------------------------------------- @@ -291,7 +297,7 @@ protected ReferenceEntry createEntry(final HashEntry map = TransformedSortedMap + final SortedMap map1 = TransformedSortedMap .transformingSortedMap( new TreeMap(), (Transformer) TransformedCollectionTest.STRING_TO_INTEGER_TRANSFORMER, null); - assertEquals(0, map.size()); + assertEquals(0, map1.size()); for (int i = 0; i < els.length; i++) { - map.put((K) els[i], (V) els[i]); - assertEquals(i + 1, map.size()); - assertEquals(true, map.containsKey(Integer.valueOf((String) els[i]))); - try { - map.containsKey(els[i]); - fail(); - } catch (final ClassCastException ex) {} - assertEquals(true, map.containsValue(els[i])); - assertEquals(els[i], map.get(Integer.valueOf((String) els[i]))); + map1.put((K) els[i], (V) els[i]); + assertEquals(i + 1, map1.size()); + assertTrue(map1.containsKey(Integer.valueOf((String) els[i]))); + final Object key = els[i]; + Exception exception = assertThrows(ClassCastException.class, () -> { + map1.containsKey(key); + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("cannot be cast to")); + } + assertTrue(map1.containsValue(els[i])); + assertEquals(els[i], map1.get(Integer.valueOf((String) els[i]))); } - try { + Exception exception = assertThrows(NullPointerException.class, () -> { map.remove(els[0]); - fail(); - } catch (final ClassCastException ex) {} - assertEquals(els[0], map.remove(Integer.valueOf((String) els[0]))); + }); + assertNull(exception.getMessage()); + assertEquals(els[0], map1.remove(Integer.valueOf((String) els[0]))); - map = TransformedSortedMap + SortedMap map = TransformedSortedMap .transformingSortedMap( new TreeMap(), null, diff --git a/src/test/java/org/apache/commons/collections4/map/UnmodifiableMapTest.java b/src/test/java/org/apache/commons/collections4/map/UnmodifiableMapTest.java index 73a64e3ba1..e01499741e 100644 --- a/src/test/java/org/apache/commons/collections4/map/UnmodifiableMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/UnmodifiableMapTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import java.util.Map; @@ -74,10 +77,10 @@ public void testDecorateFactory() { final Map map = makeFullMap(); assertSame(map, UnmodifiableMap.unmodifiableMap(map)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableMap.unmodifiableMap(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("map")); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/map/UnmodifiableOrderedMapTest.java b/src/test/java/org/apache/commons/collections4/map/UnmodifiableOrderedMapTest.java index f186359d3e..f4a69c5431 100644 --- a/src/test/java/org/apache/commons/collections4/map/UnmodifiableOrderedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/UnmodifiableOrderedMapTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashMap; import org.apache.commons.collections4.OrderedMap; @@ -73,10 +76,10 @@ public void testDecorateFactory() { final OrderedMap map = makeFullMap(); assertSame(map, UnmodifiableOrderedMap.unmodifiableOrderedMap(map)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableOrderedMap.unmodifiableOrderedMap(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("map")); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/map/UnmodifiableSortedMapTest.java b/src/test/java/org/apache/commons/collections4/map/UnmodifiableSortedMapTest.java index 3d997d7e43..3f6be3251b 100644 --- a/src/test/java/org/apache/commons/collections4/map/UnmodifiableSortedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/UnmodifiableSortedMapTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.map; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.SortedMap; import java.util.TreeMap; @@ -73,10 +76,10 @@ public void testDecorateFactory() { final SortedMap map = makeFullMap(); assertSame(map, UnmodifiableSortedMap.unmodifiableSortedMap(map)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableSortedMap.unmodifiableSortedMap(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("map")); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/multimap/AbstractMultiValuedMapTest.java b/src/test/java/org/apache/commons/collections4/multimap/AbstractMultiValuedMapTest.java index 0d845ec797..51ac076dac 100644 --- a/src/test/java/org/apache/commons/collections4/multimap/AbstractMultiValuedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/multimap/AbstractMultiValuedMapTest.java @@ -16,6 +16,13 @@ */ package org.apache.commons.collections4.multimap; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -509,36 +516,36 @@ public void testSize_Key() { // public void testIterator_Key() { // final MultiValuedMap map = makeFullMap(); // Iterator it = map.iterator("one"); -// assertEquals(true, it.hasNext()); +// assertTrue(it.hasNext()); // Set values = new HashSet(); // while (it.hasNext()) { // values.add(it.next()); // } -// assertEquals(true, values.contains("un")); -// assertEquals(true, values.contains("uno")); -// assertEquals(false, map.iterator("A").hasNext()); -// assertEquals(false, map.iterator("A").hasNext()); +// assertTrue(values.contains("un")); +// assertTrue(values.contains("uno")); +// assertFalse(map.iterator("A").hasNext()); +// assertFalse(map.iterator("A").hasNext()); // if (!isAddSupported()) { // return; // } // map.put((K) "A", (V) "AA"); // it = map.iterator("A"); -// assertEquals(true, it.hasNext()); +// assertTrue(it.hasNext()); // it.next(); -// assertEquals(false, it.hasNext()); +// assertFalse(it.hasNext()); // } @SuppressWarnings("unchecked") public void testContainsValue_Key() { final MultiValuedMap map = makeFullMap(); - assertEquals(true, map.containsMapping("one", "uno")); - assertEquals(false, map.containsMapping("two", "2")); + assertTrue(map.containsMapping("one", "uno")); + assertFalse(map.containsMapping("two", "2")); if (!isAddSupported()) { return; } map.put((K) "A", (V) "AA"); - assertEquals(true, map.containsMapping("A", "AA")); - assertEquals(false, map.containsMapping("A", "AB")); + assertTrue(map.containsMapping("A", "AA")); + assertFalse(map.containsMapping("A", "AB")); } @SuppressWarnings("unchecked") @@ -555,22 +562,20 @@ public void testPutAll_Map1() { test.put((K) "key", (V) "object0"); test.putAll(original); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { final MultiValuedMap originalNull = null; test.putAll(originalNull); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("map")); assertEquals(2, test.keySet().size()); assertEquals(4, test.size()); assertEquals(1, test.get((K) "keyA").size()); assertEquals(3, test.get((K) "key").size()); - assertEquals(true, test.containsValue("objectA")); - assertEquals(true, test.containsValue("object0")); - assertEquals(true, test.containsValue("object1")); - assertEquals(true, test.containsValue("object2")); + assertTrue(test.containsValue("objectA")); + assertTrue(test.containsValue("object0")); + assertTrue(test.containsValue("object1")); + assertTrue(test.containsValue("object2")); } @SuppressWarnings("unchecked") @@ -587,23 +592,21 @@ public void testPutAll_Map2() { test.put((K) "keyX", (V) "object0"); test.putAll(original); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { final Map originalNull = null; test.putAll(originalNull); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("map")); assertEquals(3, test.keySet().size()); assertEquals(4, test.size()); assertEquals(1, test.get((K) "keyA").size()); assertEquals(2, test.get((K) "keyX").size()); assertEquals(1, test.get((K) "keyY").size()); - assertEquals(true, test.containsValue("objectA")); - assertEquals(true, test.containsValue("object0")); - assertEquals(true, test.containsValue("object1")); - assertEquals(true, test.containsValue("object2")); + assertTrue(test.containsValue("objectA")); + assertTrue(test.containsValue("object0")); + assertTrue(test.containsValue("object1")); + assertTrue(test.containsValue("object2")); } @SuppressWarnings("unchecked") @@ -614,37 +617,35 @@ public void testPutAll_KeyIterable() { final MultiValuedMap map = makeObject(); Collection coll = (Collection) Arrays.asList("X", "Y", "Z"); - assertEquals(true, map.putAll((K) "A", coll)); + assertTrue(map.putAll((K) "A", coll)); assertEquals(3, map.get((K) "A").size()); - assertEquals(true, map.containsMapping("A", "X")); - assertEquals(true, map.containsMapping("A", "Y")); - assertEquals(true, map.containsMapping("A", "Z")); + assertTrue(map.containsMapping("A", "X")); + assertTrue(map.containsMapping("A", "Y")); + assertTrue(map.containsMapping("A", "Z")); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { map.putAll((K) "A", null); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("values")); assertEquals(3, map.get((K) "A").size()); - assertEquals(true, map.containsMapping("A", "X")); - assertEquals(true, map.containsMapping("A", "Y")); - assertEquals(true, map.containsMapping("A", "Z")); + assertTrue(map.containsMapping("A", "X")); + assertTrue(map.containsMapping("A", "Y")); + assertTrue(map.containsMapping("A", "Z")); - assertEquals(false, map.putAll((K) "A", new ArrayList())); + assertFalse(map.putAll((K) "A", new ArrayList())); assertEquals(3, map.get((K) "A").size()); - assertEquals(true, map.containsMapping("A", "X")); - assertEquals(true, map.containsMapping("A", "Y")); - assertEquals(true, map.containsMapping("A", "Z")); + assertTrue(map.containsMapping("A", "X")); + assertTrue(map.containsMapping("A", "Y")); + assertTrue(map.containsMapping("A", "Z")); coll = (Collection) Arrays.asList("M"); - assertEquals(true, map.putAll((K) "A", coll)); + assertTrue(map.putAll((K) "A", coll)); assertEquals(4, map.get((K) "A").size()); - assertEquals(true, map.containsMapping("A", "X")); - assertEquals(true, map.containsMapping("A", "Y")); - assertEquals(true, map.containsMapping("A", "Z")); - assertEquals(true, map.containsMapping("A", "M")); + assertTrue(map.containsMapping("A", "X")); + assertTrue(map.containsMapping("A", "Y")); + assertTrue(map.containsMapping("A", "Z")); + assertTrue(map.containsMapping("A", "M")); } @SuppressWarnings("unchecked") @@ -656,11 +657,11 @@ public void testRemove_KeyItem() { map.put((K) "A", (V) "AA"); map.put((K) "A", (V) "AB"); map.put((K) "A", (V) "AC"); - assertEquals(false, map.removeMapping("C", "CA")); - assertEquals(false, map.removeMapping("A", "AD")); - assertEquals(true, map.removeMapping("A", "AC")); - assertEquals(true, map.removeMapping("A", "AB")); - assertEquals(true, map.removeMapping("A", "AA")); + assertFalse(map.removeMapping("C", "CA")); + assertFalse(map.removeMapping("A", "AD")); + assertTrue(map.removeMapping("A", "AC")); + assertTrue(map.removeMapping("A", "AB")); + assertTrue(map.removeMapping("A", "AA")); //assertEquals(new MultiValuedHashMap(), map); } @@ -677,13 +678,11 @@ public void testToString(){ map.put((K) "B", (V) "W"); assertEquals("{A=[X, Y, Z], B=[U, V, W]}", map.toString()); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { final MultiValuedMap originalNull = null; map.putAll(originalNull); - fail("expecting NullPointerException"); - } catch (final NullPointerException npe) { - // expected - } + }); + assertTrue(exception.getMessage().contains("map")); assertEquals("{A=[X, Y, Z], B=[U, V, W]}", map.toString()); map.remove("A"); @@ -780,10 +779,11 @@ public void testMapIteratorUnsupportedSet() { resetFull(); final MapIterator mapIt = getMap().mapIterator(); mapIt.next(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { mapIt.setValue((V) "some value"); - fail(); - } catch (final UnsupportedOperationException e) { + }); + if (null != exception.getMessage()) { + assertTrue(exception.getMessage().contains("setValue() is not supported")); } } @@ -791,22 +791,19 @@ public void testMultiValuedMapIterator() { final MultiValuedMap map = makeFullMap(); final MapIterator it = map.mapIterator(); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.getKey(); - fail(); - } catch (final IllegalStateException ise) { - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(IllegalStateException.class, () -> { it.getValue(); - fail(); - } catch (final IllegalStateException ise) { - } + }); + assertNull(exception.getMessage()); if (isAddSupported()) { - try { + exception = assertThrows(IllegalStateException.class, () -> { it.setValue((V) "V"); - fail(); - } catch (final IllegalStateException ise) { - } + }); + assertNull(exception.getMessage()); } if (!isHashSetValue() && isAddSupported()) { @@ -829,11 +826,10 @@ public void testMultiValuedMapIterator() { assertEquals("three", it.next()); assertEquals("three", it.getKey()); assertEquals("trois", it.getValue()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { it.setValue((V) "threetrois"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); } } diff --git a/src/test/java/org/apache/commons/collections4/multimap/UnmodifiableMultiValuedMapTest.java b/src/test/java/org/apache/commons/collections4/multimap/UnmodifiableMultiValuedMapTest.java index 1fcbe20f52..ece4792e76 100644 --- a/src/test/java/org/apache/commons/collections4/multimap/UnmodifiableMultiValuedMapTest.java +++ b/src/test/java/org/apache/commons/collections4/multimap/UnmodifiableMultiValuedMapTest.java @@ -16,6 +16,12 @@ */ package org.apache.commons.collections4.multimap; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Set; import java.util.Map; import java.util.Map.Entry; @@ -83,57 +89,51 @@ public void testDecorateFactory() { } public void testDecoratorFactoryNullMap() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableMultiValuedMap.unmodifiableMultiValuedMap(null); - fail("map must not be null"); - } catch (final NullPointerException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("map")); } @SuppressWarnings("unchecked") public void testAddException() { final MultiValuedMap map = makeObject(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { map.put((K) "one", (V) "uno"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); } public void testRemoveException() { final MultiValuedMap map = makeFullMap(); - try { + // expected, not support remove() method + // UnmodifiableMultiValuedMap does not support change + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { map.remove("one"); - fail(); - } catch (final UnsupportedOperationException e) { - // expected, not support remove() method - // UnmodifiableMultiValuedMap does not support change - } + }); + assertNull(exception.getMessage()); assertEquals("{one=[uno, un], two=[dos, deux], three=[tres, trois]}", map.toString()); } public void testRemoveMappingException() { final MultiValuedMap map = makeFullMap(); - try { + // expected, not support removeMapping() method + // UnmodifiableMultiValuedMap does not support change + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { map.removeMapping("one", "uno"); - fail(); - } catch (final UnsupportedOperationException e) { - // expected, not support removeMapping() method - // UnmodifiableMultiValuedMap does not support change - } + }); + assertNull(exception.getMessage()); assertEquals("{one=[uno, un], two=[dos, deux], three=[tres, trois]}", map.toString()); } public void testClearException() { final MultiValuedMap map = makeFullMap(); - try { + // expected, not support clear() method + // UnmodifiableMultiValuedMap does not support change + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { map.clear(); - fail(); - } catch (final UnsupportedOperationException e) { - // expected, not support clear() method - // UnmodifiableMultiValuedMap does not support change - } + }); + assertNull(exception.getMessage()); assertEquals("{one=[uno, un], two=[dos, deux], three=[tres, trois]}", map.toString()); } @@ -147,29 +147,24 @@ public void testPutAllException() { originalMap.put((K) "keyX", (V) "object1"); originalMap.put((K) "keyY", (V) "object2"); - try { + // expected, not support putAll() method + // UnmodifiableMultiValuedMap does not support change + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { map.putAll(original); - fail(); - } catch (final UnsupportedOperationException e) { - // expected, not support putAll() method - // UnmodifiableMultiValuedMap does not support change - } + }); + assertNull(exception.getMessage()); assertEquals("{}", map.toString()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { map.putAll(originalMap); - fail(); - } catch (final UnsupportedOperationException e) { - // expected - } + }); + assertNull(exception.getMessage()); assertEquals("{}", map.toString()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { map.putAll((K) "A", coll); - fail(); - } catch (final UnsupportedOperationException e) { - // expected - } + }); + assertNull(exception.getMessage()); assertEquals("{}", map.toString()); } @@ -177,161 +172,140 @@ public void testPutAllException() { public void testUnmodifiableEntries() { resetFull(); final Collection> entries = getMap().entries(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { entries.clear(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); final Iterator> it = entries.iterator(); final Entry entry = it.next(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { it.remove(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { entry.setValue((V) "three"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") public void testUnmodifiableMapIterator() { resetFull(); final MapIterator mapIt = getMap().mapIterator(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { mapIt.remove(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { mapIt.setValue((V) "three"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertTrue(exception.getMessage().contains("setValue() is not supported")); } @SuppressWarnings("unchecked") public void testUnmodifiableKeySet() { resetFull(); final Set keySet = getMap().keySet(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { keySet.add((K) "four"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { keySet.remove("four"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { keySet.clear(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); final Iterator it = keySet.iterator(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { it.remove(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); } @SuppressWarnings("unchecked") public void testUnmodifiableValues() { resetFull(); final Collection values = getMap().values(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { values.add((V) "four"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { values.remove("four"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { values.clear(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); final Iterator it = values.iterator(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { it.remove(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); } @SuppressWarnings("unchecked") public void testUnmodifiableAsMap() { resetFull(); final Map> mapCol = getMap().asMap(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { mapCol.put((K) "four", (Collection) Arrays.asList("four")); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { mapCol.remove("four"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { mapCol.clear(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { mapCol.clear(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") public void testUnmodifiableKeys() { resetFull(); final MultiSet keys = getMap().keys(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { keys.add((K) "four"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { keys.remove("four"); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { keys.clear(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertNull(exception.getMessage()); final Iterator it = keys.iterator(); - try { + exception = assertThrows(UnsupportedOperationException.class, () -> { it.remove(); - fail(); - } catch (final UnsupportedOperationException e) { - } + }); + assertTrue(exception.getMessage().contains("remove() is not supported")); } // public void testCreate() throws Exception { diff --git a/src/test/java/org/apache/commons/collections4/multiset/AbstractMultiSetTest.java b/src/test/java/org/apache/commons/collections4/multiset/AbstractMultiSetTest.java index 161883f9d8..ea1036ba13 100644 --- a/src/test/java/org/apache/commons/collections4/multiset/AbstractMultiSetTest.java +++ b/src/test/java/org/apache/commons/collections4/multiset/AbstractMultiSetTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.multiset; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; @@ -138,10 +142,10 @@ public void testMultiSetAdd() { final MultiSet multiset = makeObject(); multiset.add((T) "A"); - assertTrue("Should contain 'A'", multiset.contains("A")); + assertTrue(multiset.contains("A")); assertEquals("Should have count of 1", 1, multiset.getCount("A")); multiset.add((T) "A"); - assertTrue("Should contain 'A'", multiset.contains("A")); + assertTrue(multiset.contains("A")); assertEquals("Should have count of 2", 2, multiset.getCount("A")); multiset.add((T) "B"); assertTrue(multiset.contains("A")); @@ -360,7 +364,7 @@ public void testMultiSetIterator() { } } - assertTrue("MultiSet should still contain 'A'", multiset.contains("A")); + assertTrue(multiset.contains("A")); assertEquals("MultiSet should have 2 items", 2, multiset.size()); assertEquals("MultiSet should have 1 'A'", 1, multiset.getCount("A")); } @@ -378,12 +382,10 @@ public void testMultiSetIteratorFail() { final Iterator it = multiset.iterator(); it.next(); multiset.remove("A"); - try { + Exception exception = assertThrows(ConcurrentModificationException.class, () -> { it.next(); - fail("Should throw ConcurrentModificationException"); - } catch (final ConcurrentModificationException e) { - // expected - } + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -400,12 +402,10 @@ public void testMultiSetIteratorFailNoMore() { it.next(); it.next(); it.next(); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { it.next(); - fail("Should throw NoSuchElementException"); - } catch (final NoSuchElementException ex) { - // expected - } + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -424,12 +424,10 @@ public void testMultiSetIteratorFailDoubleRemove() { assertEquals(3, multiset.size()); it.remove(); assertEquals(2, multiset.size()); - try { + Exception exception = assertThrows(IllegalStateException.class, () -> { it.remove(); - fail("Should throw IllegalStateException"); - } catch (final IllegalStateException ex) { - // expected - } + }); + assertNull(exception.getMessage()); assertEquals(2, multiset.size()); it.next(); it.remove(); @@ -696,7 +694,7 @@ public void testEmptyMultiSetCompatibility() throws IOException, ClassNotFoundEx final MultiSet multiset = makeObject(); if (multiset instanceof Serializable && !skipSerializedCanonicalTests() && isTestSerialization()) { final MultiSet multiset2 = (MultiSet) readExternalFormFromDisk(getCanonicalEmptyCollectionName(multiset)); - assertTrue("MultiSet is empty", multiset2.size() == 0); + assertTrue(multiset2.size() == 0); assertEquals(multiset, multiset2); } } diff --git a/src/test/java/org/apache/commons/collections4/multiset/PredicatedMultiSetTest.java b/src/test/java/org/apache/commons/collections4/multiset/PredicatedMultiSetTest.java index befa431c5a..6a7b539f61 100644 --- a/src/test/java/org/apache/commons/collections4/multiset/PredicatedMultiSetTest.java +++ b/src/test/java/org/apache/commons/collections4/multiset/PredicatedMultiSetTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.multiset; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Set; import junit.framework.Test; @@ -75,25 +78,21 @@ public void testLegalAddRemove() { assertEquals(true, multiset.contains(els[i])); } Set set = ((PredicatedMultiSet) multiset).uniqueSet(); - assertTrue("Unique set contains the first element", set.contains(els[0])); + assertTrue(set.contains(els[0])); assertEquals(true, multiset.remove(els[0])); set = ((PredicatedMultiSet) multiset).uniqueSet(); - assertTrue("Unique set does not contain anymore the first element", - set.contains(els[0])); + assertTrue(set.contains(els[0])); } @SuppressWarnings("unchecked") public void testIllegalAdd() { final MultiSet multiset = makeTestMultiSet(); final Integer i = Integer.valueOf(3); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { multiset.add((T) i); - fail("Integer should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - assertTrue("Collection shouldn't contain illegal element", - !multiset.contains(i)); + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3'")); + assertTrue(!multiset.contains(i)); } @SuppressWarnings("unchecked") @@ -103,18 +102,14 @@ public void testIllegalDecorate() { elements.add("two"); elements.add(Integer.valueOf(3)); elements.add("four"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { decorateMultiSet((HashMultiSet) elements, stringPredicate()); - fail("MultiSet contains an element that should fail the predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3'")); + exception = assertThrows(NullPointerException.class, () -> { decorateMultiSet(new HashMultiSet(), null); - fail("Expecting NullPointerException for null predicate."); - } catch (final NullPointerException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("predicate")); } @Override diff --git a/src/test/java/org/apache/commons/collections4/multiset/UnmodifiableMultiSetTest.java b/src/test/java/org/apache/commons/collections4/multiset/UnmodifiableMultiSetTest.java index ff2166bf82..35bd46fa9c 100644 --- a/src/test/java/org/apache/commons/collections4/multiset/UnmodifiableMultiSetTest.java +++ b/src/test/java/org/apache/commons/collections4/multiset/UnmodifiableMultiSetTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.multiset; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import junit.framework.Test; @@ -84,10 +88,10 @@ public void testDecorateFactory() { final MultiSet multiset = makeFullCollection(); assertSame(multiset, UnmodifiableMultiSet.unmodifiableMultiSet(multiset)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableMultiSet.unmodifiableMultiSet(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("collection")); } //----------------------------------------------------------------------- @@ -95,28 +99,28 @@ public void testDecorateFactory() { public void testAdd() { final MultiSet multiset = makeFullCollection(); final MultiSet unmodifiableMultiSet = UnmodifiableMultiSet.unmodifiableMultiSet(multiset); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { unmodifiableMultiSet.add((E) "One", 1); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); } public void testRemove() { final MultiSet multiset = makeFullCollection(); final MultiSet unmodifiableMultiSet = UnmodifiableMultiSet.unmodifiableMultiSet(multiset); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { unmodifiableMultiSet.remove("One", 1); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); } public void testSetCount() { final MultiSet multiset = makeFullCollection(); final MultiSet unmodifiableMultiSet = UnmodifiableMultiSet.unmodifiableMultiSet(multiset); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { unmodifiableMultiSet.setCount((E) "One", 2); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); } public void testEntrySet() { diff --git a/src/test/java/org/apache/commons/collections4/queue/AbstractQueueTest.java b/src/test/java/org/apache/commons/collections4/queue/AbstractQueueTest.java index 9fa8063c76..73b9e9ddcf 100644 --- a/src/test/java/org/apache/commons/collections4/queue/AbstractQueueTest.java +++ b/src/test/java/org/apache/commons/collections4/queue/AbstractQueueTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.queue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; @@ -169,11 +173,13 @@ public void testQueueOffer() { public void testQueueElement() { resetEmpty(); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { getCollection().element(); - fail("Queue.element should throw NoSuchElementException"); - } catch (final NoSuchElementException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("queue is empty")); } resetFull(); @@ -200,11 +206,13 @@ public void testQueueElement() { verify(); } - try { + exception = assertThrows(NoSuchElementException.class, () -> { getCollection().element(); - fail("Queue.element should throw NoSuchElementException"); - } catch (final NoSuchElementException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("queue is empty")); } } @@ -253,11 +261,13 @@ public void testQueueRemove() { resetEmpty(); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { getCollection().remove(); - fail("Queue.remove should throw NoSuchElementException"); - } catch (final NoSuchElementException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("queue is empty")); } resetFull(); @@ -270,11 +280,13 @@ public void testQueueRemove() { verify(); } - try { + exception = assertThrows(NoSuchElementException.class, () -> { getCollection().element(); - fail("Queue.remove should throw NoSuchElementException"); - } catch (final NoSuchElementException e) { - // expected + }); + if (null == exception.getMessage()) { + assertNull(exception.getMessage()); + } else { + assertTrue(exception.getMessage().contains("queue is empty")); } } diff --git a/src/test/java/org/apache/commons/collections4/queue/CircularFifoQueueTest.java b/src/test/java/org/apache/commons/collections4/queue/CircularFifoQueueTest.java index ac9796e006..0b5c24271f 100644 --- a/src/test/java/org/apache/commons/collections4/queue/CircularFifoQueueTest.java +++ b/src/test/java/org/apache/commons/collections4/queue/CircularFifoQueueTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.queue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; @@ -150,48 +154,40 @@ public void testCircularFifoQueueRemove() { verify(); } - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { getCollection().remove(); - fail("Empty queue should raise Underflow."); - } catch (final NoSuchElementException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("queue is empty")); } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException1() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new CircularFifoQueue(0); - } catch (final IllegalArgumentException ex) { - return; - } - fail(); + }); + assertTrue(exception.getMessage().contains("The size must be greater than 0")); } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException2() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new CircularFifoQueue(-20); - } catch (final IllegalArgumentException ex) { - return; - } - fail(); + }); + assertTrue(exception.getMessage().contains("The size must be greater than 0")); } /** * Tests that the constructor correctly throws an exception. */ public void testConstructorException3() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { new CircularFifoQueue(null); - } catch (final NullPointerException ex) { - return; - } - fail(); + }); + assertNull(exception.getMessage()); } @SuppressWarnings("unchecked") @@ -424,13 +420,10 @@ public void testGetIndex() { public void testAddNull() { final CircularFifoQueue b = new CircularFifoQueue<>(2); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { b.add(null); - fail(); - } catch (final NullPointerException ex) { - return; - } - fail(); + }); + assertTrue(exception.getMessage().contains("element")); } public void testDefaultSizeAndGetError1() { @@ -442,12 +435,10 @@ public void testDefaultSizeAndGetError1() { fifo.add((E) "4"); fifo.add((E) "5"); assertEquals(5, fifo.size()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { fifo.get(5); - } catch (final NoSuchElementException ex) { - return; - } - fail(); + }); + assertTrue(exception.getMessage().contains("The specified index 5 is outside the available range [0, 5)")); } public void testDefaultSizeAndGetError2() { @@ -459,12 +450,10 @@ public void testDefaultSizeAndGetError2() { fifo.add((E) "4"); fifo.add((E) "5"); assertEquals(5, fifo.size()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { fifo.get(-2); - } catch (final NoSuchElementException ex) { - return; - } - fail(); + }); + assertTrue(exception.getMessage().contains("The specified index -2 is outside the available range [0, 5)")); } @Override diff --git a/src/test/java/org/apache/commons/collections4/queue/UnmodifiableQueueTest.java b/src/test/java/org/apache/commons/collections4/queue/UnmodifiableQueueTest.java index 8bfe133ee4..2bd188dbbe 100644 --- a/src/test/java/org/apache/commons/collections4/queue/UnmodifiableQueueTest.java +++ b/src/test/java/org/apache/commons/collections4/queue/UnmodifiableQueueTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.queue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; @@ -85,10 +88,10 @@ public boolean isNullSupported() { @Override public void testQueueRemove() { resetEmpty(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { getCollection().remove(); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); } public void testUnmodifiable() { @@ -100,27 +103,27 @@ public void testDecorateFactory() { final Queue queue = makeFullCollection(); assertSame(queue, UnmodifiableQueue.unmodifiableQueue(queue)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableQueue.unmodifiableQueue(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("collection")); } public void testOffer() { final Queue queue = makeFullCollection(); final E e = null; - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { queue.offer(e); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); } public void testPoll() { final Queue queue = makeFullCollection(); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { queue.poll(); - fail(); - } catch (final UnsupportedOperationException ex) {} + }); + assertNull(exception.getMessage()); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/set/AbstractSetTest.java b/src/test/java/org/apache/commons/collections4/set/AbstractSetTest.java index 089b919fa2..27a0d12211 100644 --- a/src/test/java/org/apache/commons/collections4/set/AbstractSetTest.java +++ b/src/test/java/org/apache/commons/collections4/set/AbstractSetTest.java @@ -63,7 +63,7 @@ public void verify() { getConfirmed().hashCode(), getCollection().hashCode()); final Collection set = makeConfirmedCollection(); for (final E element : getCollection()) { - assertTrue("Set.iterator should only return unique elements", set.add(element)); + assertTrue(set.add(element)); } } @@ -150,7 +150,7 @@ public void testSetEquals() { final Collection set2 = makeConfirmedCollection(); set2.add((E) "foo"); - assertTrue("Empty set shouldn't equal nonempty set", !getCollection().equals(set2)); + assertTrue(!getCollection().equals(set2)); resetFull(); assertEquals("Full sets should be equal", getCollection(), getConfirmed()); @@ -158,7 +158,7 @@ public void testSetEquals() { set2.clear(); set2.addAll(Arrays.asList(getOtherElements())); - assertTrue("Sets with different contents shouldn't be equal", !getCollection().equals(set2)); + assertTrue(!getCollection().equals(set2)); } /** diff --git a/src/test/java/org/apache/commons/collections4/set/CompositeSetTest.java b/src/test/java/org/apache/commons/collections4/set/CompositeSetTest.java index 5b0e21d7bf..635555cb50 100644 --- a/src/test/java/org/apache/commons/collections4/set/CompositeSetTest.java +++ b/src/test/java/org/apache/commons/collections4/set/CompositeSetTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.set; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Collection; import java.util.HashSet; import java.util.List; @@ -129,12 +133,10 @@ public boolean addAll(final CompositeSet composite, final HashSet three = new HashSet<>(); three.add((E) "1"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { set.addComposited(three); - fail("IllegalArgumentException should have been thrown"); - } catch (final IllegalArgumentException e) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Attempt to add illegal entry unresolved by SetMutator.resolveCollision()")); } @SuppressWarnings("unchecked") @@ -159,12 +161,10 @@ public void testAddComposited() { final CompositeSet set5 = new CompositeSet<>(set3); set5.addComposited(set4); assertTrue(set.equals(set5)); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { set.addComposited(set3); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Collision adding composited set with no SetMutator set")); } @SuppressWarnings("unchecked") @@ -176,18 +176,14 @@ public void testAddCompositedCollision() { final HashSet set2 = new HashSet<>(); set2.add((E) "4"); final CompositeSet set3 = new CompositeSet<>(set1); - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { set3.addComposited(set1, buildOne()); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException ex) { - // expected - } - try { + }); + assertTrue(exception.getMessage().contains("Collision adding composited set with no SetMutator set")); + exception = assertThrows(UnsupportedOperationException.class, () -> { set3.addComposited(set1, buildOne(), buildTwo()); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException ex) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Collision adding composited set with no SetMutator set")); } @Override diff --git a/src/test/java/org/apache/commons/collections4/set/ListOrderedSetTest.java b/src/test/java/org/apache/commons/collections4/set/ListOrderedSetTest.java index d5547d9fc6..1402df70f1 100644 --- a/src/test/java/org/apache/commons/collections4/set/ListOrderedSetTest.java +++ b/src/test/java/org/apache/commons/collections4/set/ListOrderedSetTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.set; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; @@ -71,8 +76,7 @@ public void testOrdering() { } for (int i = 0; i < 10; i += 2) { - assertTrue("Must be able to remove int", - set.remove(Integer.toString(i))); + assertTrue(set.remove(Integer.toString(i))); } it = set.iterator(); @@ -249,31 +253,26 @@ public int hashCode() { } public void testDecorator() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ListOrderedSet.listOrderedSet((List) null); - fail(); - } catch (final NullPointerException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("list")); + exception = assertThrows(NullPointerException.class, () -> { ListOrderedSet.listOrderedSet((Set) null); - fail(); - } catch (final NullPointerException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("collection")); + exception = assertThrows(NullPointerException.class, () -> { ListOrderedSet.listOrderedSet(null, null); - fail(); - } catch (final NullPointerException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("set")); + exception = assertThrows(NullPointerException.class, () -> { ListOrderedSet.listOrderedSet(new HashSet(), null); - fail(); - } catch (final NullPointerException ex) { - } - try { + }); + assertTrue(exception.getMessage().contains("list")); + exception = assertThrows(NullPointerException.class, () -> { ListOrderedSet.listOrderedSet(null, new ArrayList()); - fail(); - } catch (final NullPointerException ex) { - } + }); + assertTrue(exception.getMessage().contains("set")); } @Override diff --git a/src/test/java/org/apache/commons/collections4/set/PredicatedNavigableSetTest.java b/src/test/java/org/apache/commons/collections4/set/PredicatedNavigableSetTest.java index c0a1c66036..8d35f3dc66 100644 --- a/src/test/java/org/apache/commons/collections4/set/PredicatedNavigableSetTest.java +++ b/src/test/java/org/apache/commons/collections4/set/PredicatedNavigableSetTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.set; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import java.util.Comparator; import java.util.NavigableSet; @@ -70,20 +74,18 @@ protected PredicatedNavigableSet makeTestSet() { public void testGetSet() { final PredicatedNavigableSet set = makeTestSet(); - assertTrue("returned set should not be null", set.decorated() != null); + assertTrue(set.decorated() != null); } @SuppressWarnings("unchecked") public void testIllegalAdd() { final NavigableSet set = makeTestSet(); final String testString = "B"; - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { set.add((E) testString); - fail("Should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - assertTrue("Collection shouldn't contain illegal element", !set.contains(testString)); + }); + assertTrue(exception.getMessage().contains("Cannot add Object 'B'")); + assertTrue(!set.contains(testString)); } @SuppressWarnings("unchecked") @@ -94,22 +96,20 @@ public void testIllegalAddAll() { elements.add((E) "Atwo"); elements.add((E) "Bthree"); elements.add((E) "Afour"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { set.addAll(elements); - fail("Should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - assertTrue("Set shouldn't contain illegal element", !set.contains("Aone")); - assertTrue("Set shouldn't contain illegal element", !set.contains("Atwo")); - assertTrue("Set shouldn't contain illegal element", !set.contains("Bthree")); - assertTrue("Set shouldn't contain illegal element", !set.contains("Afour")); + }); + assertTrue(exception.getMessage().contains("Cannot add Object 'Bthree'")); + assertTrue(!set.contains("Aone")); + assertTrue(!set.contains("Atwo")); + assertTrue(!set.contains("Bthree")); + assertTrue(!set.contains("Afour")); } public void testComparator() { final NavigableSet set = makeTestSet(); final Comparator c = set.comparator(); - assertTrue("natural order, so comparator should be null", c == null); + assertNull(c); } @Override diff --git a/src/test/java/org/apache/commons/collections4/set/PredicatedSetTest.java b/src/test/java/org/apache/commons/collections4/set/PredicatedSetTest.java index 410849f967..5af4776c0c 100644 --- a/src/test/java/org/apache/commons/collections4/set/PredicatedSetTest.java +++ b/src/test/java/org/apache/commons/collections4/set/PredicatedSetTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.set; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.HashSet; import java.util.Set; @@ -64,20 +67,18 @@ protected PredicatedSet makeTestSet() { public void testGetSet() { final PredicatedSet set = makeTestSet(); - assertTrue("returned set should not be null", set.decorated() != null); + assertTrue(set.decorated() != null); } @SuppressWarnings("unchecked") public void testIllegalAdd() { final Set set = makeTestSet(); final Integer i = Integer.valueOf(3); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { set.add((E) i); - fail("Integer should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - assertTrue("Collection shouldn't contain illegal element", !set.contains(i)); + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3'")); + assertTrue(!set.contains(i)); } @SuppressWarnings("unchecked") @@ -88,16 +89,14 @@ public void testIllegalAddAll() { elements.add((E) "two"); elements.add((E) Integer.valueOf(3)); elements.add((E) "four"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { set.addAll(elements); - fail("Integer should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - assertTrue("Set shouldn't contain illegal element", !set.contains("one")); - assertTrue("Set shouldn't contain illegal element", !set.contains("two")); - assertTrue("Set shouldn't contain illegal element", !set.contains(Integer.valueOf(3))); - assertTrue("Set shouldn't contain illegal element", !set.contains("four")); + }); + assertTrue(exception.getMessage().contains("Cannot add Object '3'")); + assertTrue(!set.contains("one")); + assertTrue(!set.contains("two")); + assertTrue(!set.contains(Integer.valueOf(3))); + assertTrue(!set.contains("four")); } @Override diff --git a/src/test/java/org/apache/commons/collections4/set/PredicatedSortedSetTest.java b/src/test/java/org/apache/commons/collections4/set/PredicatedSortedSetTest.java index 0976035b6d..6391483b3e 100644 --- a/src/test/java/org/apache/commons/collections4/set/PredicatedSortedSetTest.java +++ b/src/test/java/org/apache/commons/collections4/set/PredicatedSortedSetTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.set; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import java.util.Comparator; import java.util.Set; @@ -70,20 +74,18 @@ protected PredicatedSortedSet makeTestSet() { public void testGetSet() { final PredicatedSortedSet set = makeTestSet(); - assertTrue("returned set should not be null", set.decorated() != null); + assertTrue(set.decorated() != null); } @SuppressWarnings("unchecked") public void testIllegalAdd() { final SortedSet set = makeTestSet(); final String testString = "B"; - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { set.add((E) testString); - fail("Should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - assertTrue("Collection shouldn't contain illegal element", !set.contains(testString)); + }); + assertTrue(exception.getMessage().contains("Cannot add Object 'B'")); + assertTrue(!set.contains(testString)); } @SuppressWarnings("unchecked") @@ -94,22 +96,20 @@ public void testIllegalAddAll() { elements.add((E) "Atwo"); elements.add((E) "Bthree"); elements.add((E) "Afour"); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { set.addAll(elements); - fail("Should fail string predicate."); - } catch (final IllegalArgumentException e) { - // expected - } - assertTrue("Set shouldn't contain illegal element", !set.contains("Aone")); - assertTrue("Set shouldn't contain illegal element", !set.contains("Atwo")); - assertTrue("Set shouldn't contain illegal element", !set.contains("Bthree")); - assertTrue("Set shouldn't contain illegal element", !set.contains("Afour")); + }); + assertTrue(exception.getMessage().contains("Cannot add Object 'Bthree'")); + assertTrue(!set.contains("Aone")); + assertTrue(!set.contains("Atwo")); + assertTrue(!set.contains("Bthree")); + assertTrue(!set.contains("Afour")); } public void testComparator() { final SortedSet set = makeTestSet(); final Comparator c = set.comparator(); - assertTrue("natural order, so comparator should be null", c == null); + assertNull(c); } @Override diff --git a/src/test/java/org/apache/commons/collections4/set/UnmodifiableNavigableSetTest.java b/src/test/java/org/apache/commons/collections4/set/UnmodifiableNavigableSetTest.java index 4d0d7c63ae..2fc52549b3 100644 --- a/src/test/java/org/apache/commons/collections4/set/UnmodifiableNavigableSetTest.java +++ b/src/test/java/org/apache/commons/collections4/set/UnmodifiableNavigableSetTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.set; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -97,10 +102,10 @@ public void testDecorateFactory() { final NavigableSet set = makeFullCollection(); assertSame(set, UnmodifiableNavigableSet.unmodifiableNavigableSet(set)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableNavigableSet.unmodifiableNavigableSet(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("collection")); } /** @@ -108,48 +113,36 @@ public void testDecorateFactory() { */ @SuppressWarnings("unchecked") public void verifyUnmodifiable(final Set set) { - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { set.add((E) "value"); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { set.addAll(new TreeSet()); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { set.clear(); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { set.remove("x"); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { set.removeAll(array); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { set.retainAll(array); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } + }); + assertNull(exception.getMessage()); } public void testComparator() { setupSet(); final Comparator c = set.comparator(); - assertTrue("natural order, so comparator should be null", c == null); + assertNull(c); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/set/UnmodifiableSetTest.java b/src/test/java/org/apache/commons/collections4/set/UnmodifiableSetTest.java index 795124a586..206a7331ff 100644 --- a/src/test/java/org/apache/commons/collections4/set/UnmodifiableSetTest.java +++ b/src/test/java/org/apache/commons/collections4/set/UnmodifiableSetTest.java @@ -16,6 +16,9 @@ */ package org.apache.commons.collections4.set; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.HashSet; import java.util.Set; @@ -75,10 +78,10 @@ public void testDecorateFactory() { final Set set = makeFullCollection(); assertSame(set, UnmodifiableSet.unmodifiableSet(set)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableSet.unmodifiableSet(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("collection")); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/set/UnmodifiableSortedSetTest.java b/src/test/java/org/apache/commons/collections4/set/UnmodifiableSortedSetTest.java index ebdfbc7266..cb120ff2c9 100644 --- a/src/test/java/org/apache/commons/collections4/set/UnmodifiableSortedSetTest.java +++ b/src/test/java/org/apache/commons/collections4/set/UnmodifiableSortedSetTest.java @@ -16,6 +16,11 @@ */ package org.apache.commons.collections4.set; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; @@ -92,10 +97,10 @@ public void testDecorateFactory() { final SortedSet set = makeFullCollection(); assertSame(set, UnmodifiableSortedSet.unmodifiableSortedSet(set)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableSortedSet.unmodifiableSortedSet(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("collection")); } /** @@ -103,48 +108,36 @@ public void testDecorateFactory() { */ @SuppressWarnings("unchecked") public void verifyUnmodifiable(final Set set) { - try { + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { set.add((E) "value"); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { set.addAll(new TreeSet()); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { set.clear(); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { set.remove("x"); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { set.removeAll(array); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } - try { + }); + assertNull(exception.getMessage()); + exception = assertThrows(UnsupportedOperationException.class, () -> { set.retainAll(array); - fail("Expecting UnsupportedOperationException."); - } catch (final UnsupportedOperationException e) { - // expected - } + }); + assertNull(exception.getMessage()); } public void testComparator() { setupSet(); final Comparator c = set.comparator(); - assertTrue("natural order, so comparator should be null", c == null); + assertNull(c); } //----------------------------------------------------------------------- diff --git a/src/test/java/org/apache/commons/collections4/trie/UnmodifiableTrieTest.java b/src/test/java/org/apache/commons/collections4/trie/UnmodifiableTrieTest.java index b05ee44b81..afc9b49dd9 100644 --- a/src/test/java/org/apache/commons/collections4/trie/UnmodifiableTrieTest.java +++ b/src/test/java/org/apache/commons/collections4/trie/UnmodifiableTrieTest.java @@ -16,6 +16,8 @@ */ package org.apache.commons.collections4.trie; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import junit.framework.Test; import org.apache.commons.collections4.BulkTest; @@ -79,10 +81,10 @@ public void testDecorateFactory() { final Trie trie = makeFullMap(); assertSame(trie, UnmodifiableTrie.unmodifiableTrie(trie)); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { UnmodifiableTrie.unmodifiableTrie(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("trie")); } //-----------------------------------------------------------------------