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..9b51e990cc 100644 --- a/src/test/java/org/apache/commons/collections4/AbstractArrayListTest.java +++ b/src/test/java/org/apache/commons/collections4/AbstractArrayListTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4; +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 org.apache.commons.collections4.list.AbstractListTest; @@ -42,11 +46,11 @@ 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 + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } 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/AbstractObjectTest.java b/src/test/java/org/apache/commons/collections4/AbstractObjectTest.java index 9939b1df26..2de3853152 100644 --- a/src/test/java/org/apache/commons/collections4/AbstractObjectTest.java +++ b/src/test/java/org/apache/commons/collections4/AbstractObjectTest.java @@ -101,7 +101,7 @@ public boolean isEqualsCheckable() { //----------------------------------------------------------------------- public void testObjectEqualsSelf() { final Object obj = makeObject(); - assertEquals("A Object should equal itself", obj, obj); + assertEquals(obj, obj); } public void testEqualsNull() { @@ -111,24 +111,18 @@ public void testEqualsNull() { public void testObjectHashCodeEqualsSelfHashCode() { final Object obj = makeObject(); - assertEquals("hashCode should be repeatable", obj.hashCode(), obj.hashCode()); + assertEquals(obj.hashCode(), obj.hashCode()); } public void testObjectHashCodeEqualsContract() { final Object obj1 = makeObject(); if (obj1.equals(obj1)) { - assertEquals( - "[1] When two objects are equal, their hashCodes should be also.", - obj1.hashCode(), obj1.hashCode()); + assertEquals(obj1.hashCode(), obj1.hashCode()); } final Object obj2 = makeObject(); if (obj1.equals(obj2)) { - assertEquals( - "[2] When two objects are equal, their hashCodes should be also.", - obj1.hashCode(), obj2.hashCode()); - assertTrue( - "When obj1.equals(obj2) is true, then obj2.equals(obj1) should also be true", - obj2.equals(obj1)); + assertEquals(obj1.hashCode(), obj2.hashCode()); + assertTrue(obj2.equals(obj1)); } } @@ -150,7 +144,7 @@ public void testSerializeDeserializeThenCompare() throws Exception { if (obj instanceof Serializable && isTestSerialization()) { final Object dest = serializeDeserialize(obj); if (isEqualsCheckable()) { - assertEquals("obj != deserialize(serialize(obj))", obj, dest); + assertEquals(obj, dest); } } } @@ -180,9 +174,7 @@ public void testCanonicalEmptyCollectionExists() { final Object object = makeObject(); if (object instanceof Serializable) { final String name = getCanonicalEmptyCollectionName(object); - assertTrue( - "Canonical empty collection (" + name + ") is not in SCM", - new File(name).exists()); + assertTrue(new File(name).exists()); } } } @@ -196,9 +188,7 @@ public void testCanonicalFullCollectionExists() { final Object object = makeObject(); if (object instanceof Serializable) { final String name = getCanonicalFullCollectionName(object); - assertTrue( - "Canonical full collection (" + name + ") is not in SCM", - new File(name).exists()); + assertTrue(new File(name).exists()); } } } 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..1cac8eecc9 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.jupiter.api.Assertions.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; @@ -29,7 +31,7 @@ import org.apache.commons.collections4.bag.UnmodifiableBag; import org.apache.commons.collections4.bag.UnmodifiableSortedBag; import org.apache.commons.collections4.functors.TruePredicate; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for BagUtils factory methods. @@ -45,133 +47,117 @@ 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)); + assertSame(bag, BagUtils.unmodifiableBag(bag)); } @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)); + assertSame(bag, BagUtils.unmodifiableSortedBag(bag)); } @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 cca66abf6d..99b49d7e0d 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.jupiter.api.Assertions.assertEquals; +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.ArrayList; import java.util.Collection; @@ -29,7 +33,7 @@ import org.apache.commons.collections4.functors.FalsePredicate; import org.apache.commons.collections4.functors.NOPClosure; import org.apache.commons.collections4.functors.TruePredicate; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the ClosureUtils class. @@ -73,13 +77,11 @@ 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; - } + }); + assertTrue(exception.getMessage().contains("ExceptionClosure invoked")); } - fail(); } // nopClosure @@ -135,18 +137,20 @@ 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 { + }); + assertTrue(exception.getMessage().contains("predicate")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.whileClosure(FalsePredicate.falsePredicate(), null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("closure")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.whileClosure(null, null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().contains("predicate")); } // doWhileClosure @@ -162,10 +166,10 @@ 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) {} + }); + assertTrue(exception.getMessage().contains("predicate")); } // chainedClosure @@ -199,29 +203,33 @@ 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 { + }); + assertTrue(exception.getMessage().contains("closures[0]")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.chainedClosure((Closure[]) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("closures")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.chainedClosure((Collection>) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().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) {} + }); + assertTrue(exception.getMessage().contains("closures")); + + final Collection> collection = new ArrayList<>(); + collection.add(null); + collection.add(null); + exception = assertThrows(NullPointerException.class, () -> { + ClosureUtils.chainedClosure(collection); + }); + assertTrue(exception.getMessage().contains("closures")); } // ifClosure @@ -319,28 +327,32 @@ 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 { + }); + assertTrue(exception.getMessage().contains("predicates")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.switchClosure((Predicate[]) null, (Closure[]) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("predicates")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.switchClosure((Map, Closure>) null); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("predicatesAndClosures")); + + exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.switchClosure(new Predicate[2], new Closure[2]); - fail(); - } catch (final NullPointerException ex) {} - try { + }); + assertTrue(exception.getMessage().contains("predicates[0]")); + + exception = assertThrows(IllegalArgumentException.class, () -> { ClosureUtils.switchClosure( new Predicate[] { TruePredicate.truePredicate() }, new Closure[] { a, b }); - fail(); - } catch (final IllegalArgumentException ex) {} + }); + assertNotNull(exception.getMessage()); } // switchMapClosure @@ -380,10 +392,10 @@ public void testSwitchMapClosure() { assertEquals(NOPClosure.INSTANCE, ClosureUtils.switchMapClosure(new HashMap>())); - try { + Exception exception = assertThrows(NullPointerException.class, () -> { ClosureUtils.switchMapClosure(null); - fail(); - } catch (final NullPointerException ex) {} + }); + assertTrue(exception.getMessage().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 4922a9176c..1294d108c1 100644 --- a/src/test/java/org/apache/commons/collections4/CollectionUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/CollectionUtilsTest.java @@ -17,12 +17,14 @@ package org.apache.commons.collections4; 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.assertArrayEquals; +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.Arrays; @@ -51,9 +53,8 @@ import org.apache.commons.collections4.collection.UnmodifiableCollection; import org.apache.commons.collections4.functors.DefaultEquator; import org.apache.commons.collections4.queue.CircularFifoQueue; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for CollectionUtils. @@ -116,7 +117,7 @@ public class CollectionUtilsTest extends MockTestCase { private final Collection emptyCollection = new ArrayList<>(1); - @Before + @BeforeEach public void setUp() { collectionA = new ArrayList<>(); collectionA.add(1); @@ -192,9 +193,12 @@ public void getCardinalityMap() { assertEquals(1, (int) freqB.get(5L)); } - @Test(expected = NullPointerException.class) + @Test public void testGetCardinalityMapNull() { - CollectionUtils.getCardinalityMap(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.getCardinalityMap(null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -305,23 +309,23 @@ public void containsAll() { multiples.add("3"); 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)); - 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)); + assertFalse(CollectionUtils.containsAll(one, odds)); + assertTrue(CollectionUtils.containsAll(odds, one)); + assertFalse(CollectionUtils.containsAll(three, 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)); - assertFalse("containsAll({},{1,3}) should return false.", CollectionUtils.containsAll(empty, odds)); - assertTrue("containsAll({},{}) should return true.", CollectionUtils.containsAll(empty, empty)); + assertFalse(CollectionUtils.containsAll(two, odds)); + assertFalse(CollectionUtils.containsAll(odds, two)); + assertFalse(CollectionUtils.containsAll(one, three)); + assertFalse(CollectionUtils.containsAll(three, one)); + assertTrue(CollectionUtils.containsAll(odds, empty)); + assertFalse(CollectionUtils.containsAll(empty, odds)); + 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 @@ -337,43 +341,52 @@ 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)); - assertFalse("containsAny({1},{3}) should return false.", CollectionUtils.containsAny(one, three)); - assertFalse("containsAny({3},{1}) should return false.", CollectionUtils.containsAny(three, one)); - assertFalse("containsAny({1,3},{}) should return false.", CollectionUtils.containsAny(odds, empty)); - assertFalse("containsAny({},{1,3}) should return false.", CollectionUtils.containsAny(empty, odds)); - assertFalse("containsAny({},{}) should return false.", CollectionUtils.containsAny(empty, empty)); + assertFalse(CollectionUtils.containsAny(two, odds)); + assertFalse(CollectionUtils.containsAny(odds, two)); + assertFalse(CollectionUtils.containsAny(one, three)); + assertFalse(CollectionUtils.containsAny(three, one)); + assertFalse(CollectionUtils.containsAny(odds, empty)); + assertFalse(CollectionUtils.containsAny(empty, odds)); + assertFalse(CollectionUtils.containsAny(empty, empty)); } - @Test(expected = NullPointerException.class) + @Test public void testContainsAnyNullColl1() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.containsAny(null, list); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.containsAny(null, list); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testContainsAnyNullColl2() { final Collection list = new ArrayList<>(1); list.add("1"); final Collection list2 = null; - CollectionUtils.containsAny(list, list2); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.containsAny(list, list2); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testContainsAnyNullColl3() { final Collection list = new ArrayList<>(1); list.add("1"); final String[] array = null; - CollectionUtils.containsAny(list, array); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.containsAny(list, array); + }); + assertNotNull(exception.getMessage()); } @Test @@ -394,42 +407,51 @@ 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)); - assertFalse("containsAny({1},{3}) should return false.", CollectionUtils.containsAny(one, threeArr)); - assertFalse("containsAny({3},{1}) should return false.", CollectionUtils.containsAny(three, oneArr)); - assertFalse("containsAny({1,3},{}) should return false.", CollectionUtils.containsAny(odds, emptyArr)); - assertFalse("containsAny({},{1,3}) should return false.", CollectionUtils.containsAny(empty, oddsArr)); - assertFalse("containsAny({},{}) should return false.", CollectionUtils.containsAny(empty, emptyArr)); + assertFalse(CollectionUtils.containsAny(two, oddsArr)); + assertFalse(CollectionUtils.containsAny(odds, twoArr)); + assertFalse(CollectionUtils.containsAny(one, threeArr)); + assertFalse(CollectionUtils.containsAny(three, oneArr)); + assertFalse(CollectionUtils.containsAny(odds, emptyArr)); + assertFalse(CollectionUtils.containsAny(empty, oddsArr)); + assertFalse(CollectionUtils.containsAny(empty, emptyArr)); } - @Test(expected = NullPointerException.class) + @Test public void testContainsAnyInArrayNullColl1() { final String[] oneArr = {"1"}; - CollectionUtils.containsAny(null, oneArr); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.containsAny(null, oneArr); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testContainsAnyInArrayNullColl2() { final Collection list = new ArrayList<>(1); list.add("1"); final Collection list2 = null; - CollectionUtils.containsAny(list, list2); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.containsAny(list, list2); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testContainsAnyInArrayNullArray() { final Collection list = new ArrayList<>(1); list.add("1"); final String[] array = null; - CollectionUtils.containsAny(list, array); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.containsAny(list, array); + }); + assertNotNull(exception.getMessage()); } @Test @@ -451,18 +473,24 @@ public void union() { assertEquals(Integer.valueOf(1), freq2.get(5)); } - @Test(expected = NullPointerException.class) + @Test public void testUnionNullColl1() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.union(null, list); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.union(null, list); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testUnionNullColl2() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.union(list, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.union(list, null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -484,18 +512,24 @@ public void intersection() { assertNull(freq2.get(5)); } - @Test(expected = NullPointerException.class) + @Test public void testIntersectionNullColl1() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.intersection(null, list); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.intersection(null, list); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testIntersectionNullColl2() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.intersection(list, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.intersection(list, null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -517,18 +551,24 @@ public void disjunction() { assertEquals(Integer.valueOf(1), freq2.get(5)); } - @Test(expected = NullPointerException.class) + @Test public void testDisjunctionNullColl1() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.disjunction(null, list); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.disjunction(null, list); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testDisjunctionNullColl2() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.disjunction(list, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.disjunction(list, null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -566,18 +606,24 @@ public void testSubtract() { assertNull(freq2.get(1)); } - @Test(expected = NullPointerException.class) + @Test public void testSubtractNullColl1() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.subtract(null, list); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.subtract(null, list); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testSubtractNullColl2() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.subtract(list, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.subtract(list, null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -646,18 +692,24 @@ public void testIsSubCollection2() { assertTrue(CollectionUtils.isSubCollection(collectionA, c)); } - @Test(expected = NullPointerException.class) + @Test public void testIsSubCollectionNullColl1() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.isSubCollection(null, list); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.isSubCollection(null, list); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testIsSubCollectionNullColl2() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.isSubCollection(list, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.isSubCollection(list, null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -737,9 +789,12 @@ public int hash(final Integer o) { assertFalse(CollectionUtils.isEqualCollection(collectionA, collB, defaultEquator)); } - @Test(expected=NullPointerException.class) + @Test public void testIsEqualCollectionNullEquator() { - CollectionUtils.isEqualCollection(collectionA, collectionA, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.isEqualCollection(collectionA, collectionA, null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -783,12 +838,16 @@ public int hash(final Integer o) { assertEquals(0, CollectionUtils.hashCode(collection, e)); } - @Test(expected=NullPointerException.class) + @Test public void testHashCodeNullEquator() { - CollectionUtils.hashCode(collectionB, null); + + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.hashCode(collectionB, null); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testIsEqualCollectionNullColl1() { final Collection list = new ArrayList<>(1); list.add(1); @@ -808,10 +867,13 @@ public int hash(final Integer o) { } }; - CollectionUtils.isEqualCollection(null, list, e); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.isEqualCollection(null, list, e); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testIsEqualCollectionNullColl2() { final Collection list = new ArrayList<>(1); list.add(1); @@ -831,7 +893,10 @@ public int hash(final Integer o) { } }; - CollectionUtils.isEqualCollection(list, null, e); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.isEqualCollection(list, null, e); + }); + assertNotNull(exception.getMessage()); } @Test @@ -856,18 +921,24 @@ public void testIsProperSubCollection() { assertFalse(CollectionUtils.isProperSubCollection(a, CollectionUtils.subtract(a, b))); } - @Test(expected = NullPointerException.class) + @Test public void testIsProperSubCollectionNullColl1() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.isProperSubCollection(null, list); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.isProperSubCollection(null, list); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testIsProperSubCollectionNullColl2() { final Collection list = new ArrayList<>(1); list.add("1"); - CollectionUtils.isProperSubCollection(list, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.isProperSubCollection(list, null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -923,13 +994,16 @@ public void forAllDoIterator() { CollectionUtils.forAllDo(col.iterator(), testClosure); } - @Test(expected = FunctorException.class) + @Test @Deprecated public void forAllDoFailure() { final Closure testClosure = ClosureUtils.invokerClosure("clear"); final Collection col = new ArrayList<>(); col.add("x"); - CollectionUtils.forAllDo(col, testClosure); + Exception exception = assertThrows(FunctorException.class, () -> { + CollectionUtils.forAllDo(col, testClosure); + }); + assertNotNull(exception.getMessage()); } @Test @@ -996,18 +1070,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<>(); @@ -1025,7 +1096,7 @@ public void getFromMap() { * Tests that {@link List}s are handled correctly - e.g. using * {@link List#get(int)}. */ - @Test(expected=IndexOutOfBoundsException.class) + @Test public void getFromList() throws Exception { // List, entry exists final List list = createMock(List.class); @@ -1036,7 +1107,10 @@ public void getFromList() throws Exception { assertEquals("zero", string); assertEquals("one", CollectionUtils.get(list, 1)); // list, non-existent entry -- IndexOutOfBoundsException - CollectionUtils.get(new ArrayList<>(), 2); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(new ArrayList<>(), 2); + }); + assertNotNull(exception.getMessage()); } @Test @@ -1049,13 +1123,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 @@ -1071,16 +1145,15 @@ 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) + @Test @Deprecated public void getFromIterable() throws Exception { // Collection, entry exists @@ -1089,10 +1162,13 @@ public void getFromIterable() throws Exception { assertEquals("element", CollectionUtils.get(bag, 0)); // Collection, non-existent entry - CollectionUtils.get(bag, 1); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(bag, 1); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void getFromObjectArray() throws Exception { // Object array, entry exists final Object[] objArray = new Object[2]; @@ -1103,10 +1179,13 @@ public void getFromObjectArray() throws Exception { // Object array, non-existent entry -- // ArrayIndexOutOfBoundsException - CollectionUtils.get(objArray, 2); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(objArray, 2); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void getFromPrimitiveArray() throws Exception { // Primitive array, entry exists final int[] array = new int[2]; @@ -1117,14 +1196,20 @@ public void getFromPrimitiveArray() throws Exception { // Object array, non-existent entry -- // ArrayIndexOutOfBoundsException - CollectionUtils.get(array, 2); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get(array, 2); + }); + assertNull(exception.getMessage()); } - @Test(expected = IllegalArgumentException.class) + @Test public void getFromObject() throws Exception { // Invalid object final Object obj = new Object(); - CollectionUtils.get(obj, 0); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.get(obj, 0); + }); + assertNotNull(exception.getMessage()); } // ----------------------------------------------------------------------- @@ -1196,9 +1281,12 @@ public void testSize_Iterator() { assertEquals(2, CollectionUtils.size(list.iterator())); } - @Test(expected=IllegalArgumentException.class) + @Test public void testSize_Other() { - CollectionUtils.size("not a list"); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.size("not a list"); + }); + assertNotNull(exception.getMessage()); } // ----------------------------------------------------------------------- @@ -1273,11 +1361,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")); } // ----------------------------------------------------------------------- @@ -1427,7 +1514,7 @@ public void selectWithOutputCollections() { // rejected contains 1, 3, and 4 final Integer[] expected = {1, 3, 4}; - Assert.assertArrayEquals(expected, rejected.toArray()); + assertArrayEquals(expected, rejected.toArray()); output.clear(); rejected.clear(); @@ -1548,9 +1635,12 @@ public void addIgnoreNull() { assertTrue(set.contains("4")); } - @Test(expected = NullPointerException.class) + @Test public void testAddIgnoreNullNullColl() { - CollectionUtils.addIgnoreNull(null, "1"); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.addIgnoreNull(null, "1"); + }); + assertNotNull(exception.getMessage()); } // ----------------------------------------------------------------------- @@ -1558,19 +1648,25 @@ 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) + @Test public void testPredicatedCollectionNullColl() { final Predicate predicate = PredicateUtils.instanceofPredicate(Integer.class); - CollectionUtils.predicatedCollection(null, predicate); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.predicatedCollection(null, predicate); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testPredicatedCollectionNullPredicate() { final Collection list = new ArrayList<>(); - CollectionUtils.predicatedCollection(list, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.predicatedCollection(list, null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -1589,9 +1685,12 @@ public void isFull() { assertFalse(CollectionUtils.isFull(buf)); } - @Test(expected = NullPointerException.class) + @Test public void testIsFullNullColl() { - CollectionUtils.isFull(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.isFull(null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -1616,9 +1715,12 @@ public void maxSize() { assertEquals(3, CollectionUtils.maxSize(buf)); } - @Test(expected = NullPointerException.class) + @Test public void testMaxSizeNullColl() { - CollectionUtils.maxSize(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.maxSize(null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -1686,18 +1788,24 @@ public void testRetainAll() { assertTrue(sub.contains("X")); } - @Test(expected = NullPointerException.class) + @Test public void testRetainAllNullBaseColl() { final List sub = new ArrayList<>(); sub.add("A"); - CollectionUtils.retainAll(null, sub); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.retainAll(null, sub); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testRetainAllNullSubColl() { final List base = new ArrayList<>(); base.add("A"); - CollectionUtils.retainAll(base, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.retainAll(base, null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -1718,39 +1826,54 @@ public void testRemoveRange() { assertTrue(result.contains(3)); } - @Test(expected=NullPointerException.class) + @Test public void testRemoveRangeNull() { final Collection list = null; - CollectionUtils.removeRange(list, 0, 0); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.removeRange(list, 0, 0); + }); + assertNotNull(exception.getMessage()); } - @Test(expected=IndexOutOfBoundsException.class) + @Test public void testRemoveRangeStartIndexNegative() { final Collection list = new ArrayList<>(); list.add(1); - CollectionUtils.removeRange(list, -1, 1); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.removeRange(list, -1, 1); + }); + assertNotNull(exception.getMessage()); } - @Test(expected=IllegalArgumentException.class) + @Test public void testRemoveRangeEndIndexNegative() { final Collection list = new ArrayList<>(); list.add(1); - CollectionUtils.removeRange(list, 0, -1); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.removeRange(list, 0, -1); + }); + assertNotNull(exception.getMessage()); } - @Test(expected=IllegalArgumentException.class) + @Test public void testRemoveRangeEndLowStart() { final Collection list = new ArrayList<>(); list.add(1); list.add(2); - CollectionUtils.removeRange(list, 1, 0); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.removeRange(list, 1, 0); + }); + assertNotNull(exception.getMessage()); } - @Test(expected=IndexOutOfBoundsException.class) + @Test public void testRemoveRangeWrongEndIndex() { final Collection list = new ArrayList<>(); list.add(1); - CollectionUtils.removeRange(list, 0, 2); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.removeRange(list, 0, 2); + }); + assertNotNull(exception.getMessage()); } @Test @@ -1784,29 +1907,41 @@ public void testRemoveCount() { assertTrue(result.contains(5)); } - @Test(expected=NullPointerException.class) + @Test public void testRemoveCountWithNull() { final Collection list = null; - CollectionUtils.removeCount(list, 0, 1); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.removeCount(list, 0, 1); + }); + assertNotNull(exception.getMessage()); } - @Test(expected=IndexOutOfBoundsException.class) + @Test public void testRemoveCountStartNegative() { final Collection list = new ArrayList<>(); - CollectionUtils.removeCount(list, -1, 1); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.removeCount(list, -1, 1); + }); + assertNotNull(exception.getMessage()); } - @Test(expected=IndexOutOfBoundsException.class) + @Test public void testRemoveCountNegative() { final Collection list = new ArrayList<>(); - CollectionUtils.removeCount(list, 0, -1); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.removeCount(list, 0, -1); + }); + assertNotNull(exception.getMessage()); } - @Test(expected=IndexOutOfBoundsException.class) + @Test public void testRemoveCountWrongCount() { final Collection list = new ArrayList<>(); list.add(1); - CollectionUtils.removeCount(list, 0, 2); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.removeCount(list, 0, 2); + }); + assertNotNull(exception.getMessage()); } @Test @@ -1835,18 +1970,24 @@ public void testRemoveAll() { assertTrue(sub.contains("X")); } - @Test(expected = NullPointerException.class) + @Test public void testRemoveAllNullBaseColl() { final List sub = new ArrayList<>(); sub.add("A"); - CollectionUtils.removeAll(null, sub); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.removeAll(null, sub); + }); + assertNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testRemoveAllNullSubColl() { final List base = new ArrayList<>(); base.add("A"); - CollectionUtils.removeAll(base, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.removeAll(base, null); + }); + assertNull(exception.getMessage()); } // ----------------------------------------------------------------------- @@ -1854,19 +1995,25 @@ 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) + @Test public void testTransformingCollectionNullColl() { final Transformer transformer = TransformerUtils.nopTransformer(); - CollectionUtils.transformingCollection(null, transformer); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.transformingCollection(null, transformer); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testTransformingCollectionNullTransformer() { final List list = new ArrayList<>(); - CollectionUtils.transformingCollection(list, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.transformingCollection(list, null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -1885,26 +2032,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 @@ -1977,53 +2120,77 @@ public void addAllForElements() { assertTrue(collectionA.contains(5)); } - @Test(expected = NullPointerException.class) + @Test public void testaddAllNullColl1() { final List list = new ArrayList<>(); - CollectionUtils.addAll(null, list); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.addAll(null, list); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testAddAllNullColl2() { final List list = new ArrayList<>(); final Iterable list2 = null; - CollectionUtils.addAll(list, list2); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.addAll(list, list2); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testAddAllNullColl3() { final List list = new ArrayList<>(); final Iterator list2 = null; - CollectionUtils.addAll(list, list2); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.addAll(list, list2); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testAddAllNullColl4() { final List list = new ArrayList<>(); final Enumeration enumArray = null; - CollectionUtils.addAll(list, enumArray); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.addAll(list, enumArray); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testAddAllNullColl5() { final List list = new ArrayList<>(); final Integer[] array = null; - CollectionUtils.addAll(list, array); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.addAll(list, array); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void getNegative() { - CollectionUtils.get((Object) collectionA, -3); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get((Object) collectionA, -3); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void getPositiveOutOfBounds() { - CollectionUtils.get((Object) collectionA.iterator(), 30); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + CollectionUtils.get((Object) collectionA.iterator(), 30); + }); + assertNotNull(exception.getMessage()); } - @Test(expected = IllegalArgumentException.class) + @Test public void get1() { - CollectionUtils.get((Object) null, 0); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + CollectionUtils.get((Object) null, 0); + }); + assertNotNull(exception.getMessage()); } @Test @@ -2063,33 +2230,35 @@ public void reverse() { assertEquals(collectionA, Arrays.asList(a)); } - @Test(expected = NullPointerException.class) + @Test public void testReverseArrayNull() { - CollectionUtils.reverseArray(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.reverseArray(null); + }); + assertNotNull(exception.getMessage()); } @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")); } /** @@ -2100,45 +2269,54 @@ private void next(final Iterator iterator, final T t) { expect(iterator.next()).andReturn(t); } - @Test(expected=NullPointerException.class) + @Test public void collateException0() { - CollectionUtils.collate(null, collectionC); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.collate(null, collectionC); + }); + assertNotNull(exception.getMessage()); } - @Test(expected=NullPointerException.class) + @Test public void collateException1() { - CollectionUtils.collate(collectionA, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.collate(collectionA, null); + }); + assertNotNull(exception.getMessage()); } - @Test(expected=NullPointerException.class) + @Test public void collateException2() { - CollectionUtils.collate(collectionA, collectionC, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.collate(collectionA, collectionC, null); + }); + assertNotNull(exception.getMessage()); } @Test public void testCollate() { List result = CollectionUtils.collate(emptyCollection, emptyCollection); - assertEquals("Merge empty with empty", 0, result.size()); + assertEquals(0, result.size()); result = CollectionUtils.collate(collectionA, emptyCollection); - assertEquals("Merge empty with non-empty", collectionA, result); + assertEquals(collectionA, result); List result1 = CollectionUtils.collate(collectionD, collectionE); List result2 = CollectionUtils.collate(collectionE, collectionD); - assertEquals("Merge two lists 1", result1, result2); + assertEquals(result1, result2); final List combinedList = new ArrayList<>(); combinedList.addAll(collectionD); combinedList.addAll(collectionE); Collections.sort(combinedList); - assertEquals("Merge two lists 2", combinedList, result2); + assertEquals(combinedList, result2); final Comparator reverseComparator = ComparatorUtils.reversedComparator(ComparatorUtils.naturalComparator()); result = CollectionUtils.collate(emptyCollection, emptyCollection, reverseComparator); - assertEquals("Comparator Merge empty with empty", 0, result.size()); + assertEquals(0, result.size()); Collections.reverse((List) collectionD); Collections.reverse((List) collectionE); @@ -2146,15 +2324,15 @@ public void testCollate() { result1 = CollectionUtils.collate(collectionD, collectionE, reverseComparator); result2 = CollectionUtils.collate(collectionE, collectionD, reverseComparator); - assertEquals("Comparator Merge two lists 1", result1, result2); - assertEquals("Comparator Merge two lists 2", combinedList, result2); + assertEquals(result1, result2); + assertEquals(combinedList, result2); } @Test public void testCollateIgnoreDuplicates() { final List result1 = CollectionUtils.collate(collectionD, collectionE, false); final List result2 = CollectionUtils.collate(collectionE, collectionD, false); - assertEquals("Merge two lists 1 - ignore duplicates", result1, result2); + assertEquals(result1, result2); final Set combinedSet = new HashSet<>(); combinedSet.addAll(collectionD); @@ -2162,12 +2340,15 @@ public void testCollateIgnoreDuplicates() { final List combinedList = new ArrayList<>(combinedSet); Collections.sort(combinedList); - assertEquals("Merge two lists 2 - ignore duplicates", combinedList, result2); + assertEquals(combinedList, result2); } - @Test(expected=NullPointerException.class) + @Test public void testPermutationsWithNullCollection() { - CollectionUtils.permutations(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + CollectionUtils.permutations(null); + }); + assertNotNull(exception.getMessage()); } @Test @@ -2239,17 +2420,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 @@ -2292,17 +2471,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..25262f7c97 100644 --- a/src/test/java/org/apache/commons/collections4/ComparatorUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/ComparatorUtilsTest.java @@ -16,13 +16,14 @@ */ 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.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 org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests ComparatorUtils. @@ -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..f2e6036489 100644 --- a/src/test/java/org/apache/commons/collections4/EnumerationUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/EnumerationUtilsTest.java @@ -16,10 +16,11 @@ */ 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.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.Enumeration; @@ -29,7 +30,7 @@ import java.util.StringTokenizer; import java.util.Vector; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests EnumerationUtils. @@ -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 d57cfa8b15..af0cf5454f 100644 --- a/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/FactoryUtilsTest.java @@ -16,13 +16,13 @@ */ package org.apache.commons.collections4; -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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +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.io.IOException; import java.io.Serializable; @@ -31,7 +31,7 @@ import org.apache.commons.collections4.functors.ConstantFactory; import org.apache.commons.collections4.functors.ExceptionFactory; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the org.apache.commons.collections.FactoryUtils class. @@ -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 { @@ -214,9 +209,12 @@ public int getValue() { // instantiateFactory //------------------------------------------------------------------ - @Test(expected=NullPointerException.class) + @Test public void instantiateFactoryNull() { - FactoryUtils.instantiateFactory(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + FactoryUtils.instantiateFactory(null); + }); + assertTrue(exception.getMessage().contains("classToInstantiate")); } @Test @@ -229,14 +227,20 @@ public void instantiateFactorySimple() { assertEquals(1, created.getValue()); } - @Test(expected=IllegalArgumentException.class) + @Test public void instantiateFactoryMismatch() { - FactoryUtils.instantiateFactory(Date.class, null, new Object[] {null}); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + FactoryUtils.instantiateFactory(Date.class, null, new Object[] {null}); + }); + assertTrue(exception.getMessage().contains("Parameter types must match the arguments")); } - @Test(expected=IllegalArgumentException.class) + @Test public void instantiateFactoryNoConstructor() { - FactoryUtils.instantiateFactory(Date.class, new Class[] {Long.class}, new Object[] {null}); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + FactoryUtils.instantiateFactory(Date.class, new Class[] {Long.class}, new Object[] {null}); + }); + assertTrue(exception.getMessage().contains("InstantiateFactory: The constructor must exist and be public")); } @Test diff --git a/src/test/java/org/apache/commons/collections4/FluentIterableTest.java b/src/test/java/org/apache/commons/collections4/FluentIterableTest.java index 4b7277713f..2f52d3c54c 100644 --- a/src/test/java/org/apache/commons/collections4/FluentIterableTest.java +++ b/src/test/java/org/apache/commons/collections4/FluentIterableTest.java @@ -16,13 +16,13 @@ */ package org.apache.commons.collections4; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -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.assertArrayEquals; +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.ArrayList; import java.util.Arrays; @@ -34,8 +34,8 @@ import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for FluentIterable. @@ -69,7 +69,7 @@ public class FluentIterableTest { */ private Iterable emptyIterable = null; - @Before + @BeforeEach public void setUp() { final Collection collectionA = new ArrayList<>(); collectionA.add(1); @@ -121,12 +121,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 +162,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 +198,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 +216,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 +242,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 +280,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 +297,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 +319,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 +339,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 +368,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 +380,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 +442,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 +461,16 @@ 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()) { + 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..66335ccf27 100644 --- a/src/test/java/org/apache/commons/collections4/IterableUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/IterableUtilsTest.java @@ -17,12 +17,14 @@ package org.apache.commons.collections4; 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.assertArrayEquals; +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 static org.junit.jupiter.api.Assertions.fail; import java.util.ArrayList; import java.util.Arrays; @@ -34,9 +36,8 @@ import java.util.Set; import org.apache.commons.collections4.bag.HashBag; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for IterableUtils. @@ -60,7 +61,7 @@ public class IterableUtilsTest { */ private Iterable emptyIterable = null; - @Before + @BeforeEach public void setUp() { final Collection collectionA = new ArrayList<>(); collectionA.add(1); @@ -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); @@ -124,12 +124,15 @@ public void forEach() { IterableUtils.forEach(col, testClosure); } - @Test(expected = FunctorException.class) + @Test public void forEachFailure() { final Closure testClosure = ClosureUtils.invokerClosure("clear"); final Collection col = new ArrayList<>(); col.add("x"); - IterableUtils.forEach(col, testClosure); + Exception exception = assertThrows(FunctorException.class, () -> { + IterableUtils.forEach(col, testClosure); + }); + assertTrue(exception.getMessage().contains("InvokerTransformer")); } @Test @@ -148,12 +151,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 +193,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 +275,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 +290,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 +301,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 +339,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)); @@ -380,13 +366,16 @@ public void getFromIterable() throws Exception { assertEquals("element", IterableUtils.get(bag, 0)); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void getFromIterableIndexOutOfBoundsException() throws Exception { // Collection, entry exists final Bag bag = new HashBag<>(); bag.add("element", 1); // Collection, non-existent entry - IterableUtils.get(bag, 1); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IterableUtils.get(bag, 1); + }); + assertTrue(exception.getMessage().contains("Entry does not exist: 0")); } public void firstFromIterable() throws Exception { @@ -396,12 +385,15 @@ public void firstFromIterable() throws Exception { assertEquals("element", IterableUtils.first(bag)); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void firstFromIterableIndexOutOfBoundsException() throws Exception { // Collection, entry exists final Bag bag = new HashBag<>(); // Collection, non-existent entry - IterableUtils.first(bag); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + IterableUtils.first(bag); + }); + assertTrue(exception.getMessage().contains("Entry does not exist: 0")); } @SuppressWarnings("unchecked") @@ -423,7 +415,7 @@ public void partition() { // second partition contains 1, 3, and 4 final Integer[] expected = {1, 3, 4}; partition = partitions.get(1); - Assert.assertArrayEquals(expected, partition.toArray()); + assertArrayEquals(expected, partition.toArray()); partitions = IterableUtils.partition((List) null, EQUALS_TWO); assertEquals(2, partitions.size()); @@ -434,12 +426,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") @@ -465,7 +455,7 @@ public void partitionMultiplePredicates() { // third partition contains 1 and 3 final Integer[] expected = {1, 3}; partition = partitions.get(2); - Assert.assertArrayEquals(expected, partition.toArray()); + assertArrayEquals(expected, partition.toArray()); try { IterableUtils.partition(input, EQUALS_TWO, null); @@ -542,42 +532,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..bd3093d19f 100644 --- a/src/test/java/org/apache/commons/collections4/IteratorUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/IteratorUtilsTest.java @@ -21,12 +21,12 @@ import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; 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.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.Arrays; @@ -47,8 +47,8 @@ import org.apache.commons.collections4.iterators.*; import org.apache.commons.collections4.map.EntrySetToMapIteratorAdapter; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.w3c.dom.Node; import org.w3c.dom.NodeList; @@ -133,7 +133,7 @@ private ListIterator getImmutableListIterator() { return IteratorUtils.unmodifiableListIterator(list.listIterator()); } - @Before + @BeforeEach public void setUp() { collectionA = new ArrayList<>(); collectionA.add(1); @@ -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,31 +369,28 @@ 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) + @Test public void testAsEnumerationNull() { - IteratorUtils.asEnumeration(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.asEnumeration(null); + }); + assertTrue(exception.getMessage().contains("iterator")); } @Test @@ -459,27 +411,28 @@ public void testAsIterable() { assertTrue(expected > 0); // single use iterator - assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext()); + assertFalse(IteratorUtils.asIterable(iterator).iterator().hasNext()); } @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) + @Test public void testAsIterator() { final Vector vector = new Vector<>(); vector.addElement("zero"); vector.addElement("one"); final Enumeration en = vector.elements(); - assertTrue("create instance fail", IteratorUtils.asIterator(en) instanceof Iterator); - IteratorUtils.asIterator(null); + assertTrue(IteratorUtils.asIterator(en) instanceof Iterator); + Exception exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.asIterator(null); + }); + assertTrue(exception.getMessage().contains("enumeration")); } @Test @@ -490,7 +443,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 +485,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 +506,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(), @@ -599,7 +546,7 @@ public void testCollatedIterator() { assertEquals(combinedList, result); } - @Test(expected = NullPointerException.class) + @Test public void testCollatedIteratorCollectionNull() { final Collection> coll = new ArrayList<>(); coll.add(collectionOdd.iterator()); @@ -607,10 +554,13 @@ public void testCollatedIteratorCollectionNull() { final Iterator it = IteratorUtils.collatedIterator(null, coll); final List result = IteratorUtils.toList(it); assertEquals(6, result.size()); - IteratorUtils.collatedIterator(null, (Collection>) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.collatedIterator(null, (Collection>) null); + }); + assertNull(exception.getMessage()); } - @Test(expected = NullPointerException.class) + @Test public void testCollatedIteratorNull() { final ArrayList arrayList = new ArrayList(); // natural ordering @@ -632,7 +582,10 @@ public void testCollatedIteratorNull() { it = IteratorUtils.collatedIterator(reverseComparator, collectionOdd.iterator()); result = IteratorUtils.toList(it); assertEquals(collectionOdd, result); - IteratorUtils.collatedIterator(null, arrayList.iterator(), arrayList.listIterator(), null); + Exception exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.collatedIterator(null, arrayList.iterator(), arrayList.listIterator(), null); + }); + assertTrue(exception.getMessage().contains("iterator")); } // ----------------------------------------------------------------------- @@ -652,16 +605,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 +635,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 +675,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 +715,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 +747,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 +794,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 +816,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 +844,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 +872,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 +894,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 +910,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,32 +934,36 @@ 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) + @Test public void testLoopingIterator() { final ArrayList arrayList = new ArrayList(); arrayList.add("test"); final Collection coll = new ArrayList(); coll.add("test"); final Iterator ie = arrayList.iterator(); - assertTrue("create instance fail", IteratorUtils.loopingIterator(coll) instanceof ResettableIterator); - IteratorUtils.loopingIterator(null); + assertTrue(IteratorUtils.loopingIterator(coll) instanceof ResettableIterator); + Exception exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.loopingIterator(null); + }); + assertTrue(exception.getMessage().contains("collection")); } - @Test(expected = NullPointerException.class) + @Test 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); - IteratorUtils.loopingListIterator(null); + assertTrue(IteratorUtils.loopingListIterator(arrayList) instanceof ResettableIterator); + Exception exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.loopingListIterator(null); + }); + assertTrue(exception.getMessage().contains("list")); } /** @@ -1065,14 +988,12 @@ public void testNodeIterator() { assertTrue(expectedNodeIndex > 0); // single use iterator - assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext()); + assertFalse(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")); } /** @@ -1094,46 +1015,49 @@ public void testNodeListIterator() { assertTrue(expectedNodeIndex > 0); // single use iterator - assertFalse("should not be able to iterate twice", IteratorUtils.asIterable(iterator).iterator().hasNext()); + assertFalse(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) + @Test public void testPeekingIterator() { final ArrayList arrayList = new ArrayList(); final Iterator ie = arrayList.iterator(); - assertTrue("create instance fail", IteratorUtils.peekingIterator(ie) instanceof Iterator); - IteratorUtils.peekingIterator(null); - + assertTrue(IteratorUtils.peekingIterator(ie) instanceof Iterator); + Exception exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.peekingIterator(null); + }); + assertTrue(exception.getMessage().contains("iterator")); } - @Test(expected = NullPointerException.class) + @Test public void testPushBackIterator() { final ArrayList arrayList = new ArrayList(); final Iterator ie = arrayList.iterator(); - assertTrue("create instance fail", IteratorUtils.pushbackIterator(ie) instanceof Iterator); - IteratorUtils.pushbackIterator(null); + assertTrue(IteratorUtils.pushbackIterator(ie) instanceof Iterator); + Exception exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.pushbackIterator(null); + }); + assertTrue(exception.getMessage().contains("iterator")); } @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 +1069,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 +1084,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 +1104,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 +1133,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 +1162,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 +1210,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")); } /** @@ -1407,20 +1294,22 @@ public void testUnmodifiableListIteratorIteration() { assertTrue(listIterator.hasNext()); } - @Test(expected = NullPointerException.class) + @Test public void testUnmodifiableMapIterator() { final Set set = new LinkedHashSet<>(); final MapIterator ie = new EntrySetToMapIteratorAdapter(set); - assertTrue("create instance fail", IteratorUtils.unmodifiableMapIterator(ie) instanceof MapIterator); - IteratorUtils.unmodifiableMapIterator(null); - + assertTrue(IteratorUtils.unmodifiableMapIterator(ie) instanceof MapIterator); + Exception exception = assertThrows(NullPointerException.class, () -> { + IteratorUtils.unmodifiableMapIterator(null); + }); + assertTrue(exception.getMessage().contains("iterator")); } @Test 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..8fedf5ce60 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.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +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.Arrays; @@ -27,8 +34,8 @@ import org.apache.commons.collections4.functors.EqualPredicate; import org.apache.commons.collections4.list.PredicatedList; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for ListUtils. @@ -46,7 +53,7 @@ public class ListUtilsTest { private String[] fullArray; private List fullList; - @Before + @BeforeEach public void setUp() { fullArray = new String[]{a, b, c, d, e}; fullList = new ArrayList<>(Arrays.asList(fullArray)); @@ -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 a0789762a5..5027bd5236 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..2d30b906d0 100644 --- a/src/test/java/org/apache/commons/collections4/MultiMapUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/MultiMapUtilsTest.java @@ -16,11 +16,11 @@ */ package org.apache.commons.collections4; -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.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.Collection; @@ -29,7 +29,7 @@ import java.util.Set; import org.apache.commons.collections4.multimap.ArrayListValuedHashMap; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for MultiMapUtils @@ -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..1b67e43659 100644 --- a/src/test/java/org/apache/commons/collections4/MultiSetUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/MultiSetUtilsTest.java @@ -16,14 +16,16 @@ */ package org.apache.commons.collections4; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +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 org.apache.commons.collections4.multiset.HashMultiSet; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for MultiSetUtils. @@ -34,7 +36,7 @@ public class MultiSetUtilsTest { private String[] fullArray; private MultiSet multiSet; - @Before + @BeforeEach public void setUp() { fullArray = new String[]{ "a", "a", "b", "c", "d", "d", "d" @@ -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 af558a6731..e832c2d2df 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.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.ArrayList; import java.util.Arrays; @@ -36,7 +40,7 @@ import org.apache.commons.collections4.functors.NotNullPredicate; import org.apache.commons.collections4.functors.NullPredicate; import org.apache.commons.collections4.functors.TruePredicate; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the PredicateUtils class. @@ -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 @@ -130,9 +132,12 @@ public void testNotPredicate() { assertFalse(PredicateUtils.notPredicate(truePredicate()).evaluate(cInteger)); } - @Test(expected=NullPointerException.class) + @Test public void testNotPredicateEx() { - PredicateUtils.notPredicate(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.notPredicate(null); + }); + assertTrue(exception.getMessage().contains("predicate")); } // andPredicate @@ -146,9 +151,12 @@ public void testAndPredicate() { assertFalse(PredicateUtils.andPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); } - @Test(expected=NullPointerException.class) + @Test public void testAndPredicateEx() { - PredicateUtils.andPredicate(null, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.andPredicate(null, null); + }); + assertTrue(exception.getMessage().contains("predicate")); } // allPredicate @@ -192,25 +200,37 @@ public void testAllPredicate() { assertPredicateTrue(AllPredicate.allPredicate(coll), null); } - @Test(expected=NullPointerException.class) + @Test public void testAllPredicateEx1() { - AllPredicate.allPredicate((Predicate[]) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + AllPredicate.allPredicate((Predicate[]) null); + }); + assertTrue(exception.getMessage().contains("predicate")); } @SuppressWarnings("unchecked") - @Test(expected=NullPointerException.class) + @Test public void testAllPredicateEx2() { - AllPredicate.allPredicate(new Predicate[] { null }); + Exception exception = assertThrows(NullPointerException.class, () -> { + AllPredicate.allPredicate(new Predicate[] { null }); + }); + assertTrue(exception.getMessage().contains("predicate")); } - @Test(expected=NullPointerException.class) + @Test public void testAllPredicateEx3() { - AllPredicate.allPredicate(null, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + AllPredicate.allPredicate(null, null); + }); + assertTrue(exception.getMessage().contains("predicate")); } - @Test(expected=NullPointerException.class) + @Test public void testAllPredicateEx4() { - AllPredicate.allPredicate((Collection>) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + AllPredicate.allPredicate((Collection>) null); + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test @@ -218,12 +238,15 @@ public void testAllPredicateEx5() { AllPredicate.allPredicate(Collections.emptyList()); } - @Test(expected=NullPointerException.class) + @Test public void testAllPredicateEx6() { final Collection> coll = new ArrayList<>(); coll.add(null); coll.add(null); - AllPredicate.allPredicate(coll); + Exception exception = assertThrows(NullPointerException.class, () -> { + AllPredicate.allPredicate(coll); + }); + assertTrue(exception.getMessage().contains("predicate")); } // orPredicate @@ -237,9 +260,12 @@ public void testOrPredicate() { assertFalse(PredicateUtils.orPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); } - @Test(expected=NullPointerException.class) + @Test public void testOrPredicateEx() { - PredicateUtils.orPredicate(null, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.orPredicate(null, null); + }); + assertTrue(exception.getMessage().contains("predicate")); } // anyPredicate @@ -284,25 +310,37 @@ public void testAnyPredicate() { assertPredicateFalse(PredicateUtils.anyPredicate(coll), null); } - @Test(expected=NullPointerException.class) + @Test public void testAnyPredicateEx1() { - PredicateUtils.anyPredicate((Predicate[]) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.anyPredicate((Predicate[]) null); + }); + assertTrue(exception.getMessage().contains("predicate")); } @SuppressWarnings("unchecked") - @Test(expected=NullPointerException.class) + @Test public void testAnyPredicateEx2() { - PredicateUtils.anyPredicate(new Predicate[] {null}); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.anyPredicate(new Predicate[] {null}); + }); + assertTrue(exception.getMessage().contains("predicate")); } - @Test(expected=NullPointerException.class) + @Test public void testAnyPredicateEx3() { - PredicateUtils.anyPredicate(null, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.anyPredicate(null, null); + }); + assertTrue(exception.getMessage().contains("predicate")); } - @Test(expected=NullPointerException.class) + @Test public void testAnyPredicateEx4() { - PredicateUtils.anyPredicate((Collection>) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.anyPredicate((Collection>) null); + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test @@ -310,12 +348,15 @@ public void testAnyPredicateEx5() { PredicateUtils.anyPredicate(Collections.emptyList()); } - @Test(expected=NullPointerException.class) + @Test public void testAnyPredicateEx6() { final Collection> coll = new ArrayList<>(); coll.add(null); coll.add(null); - PredicateUtils.anyPredicate(coll); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.anyPredicate(coll); + }); + assertTrue(exception.getMessage().contains("predicate")); } // eitherPredicate @@ -329,9 +370,12 @@ public void testEitherPredicate() { assertFalse(PredicateUtils.eitherPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); } - @Test(expected=NullPointerException.class) + @Test public void testEitherPredicateEx() { - PredicateUtils.eitherPredicate(null, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.eitherPredicate(null, null); + }); + assertTrue(exception.getMessage().contains("predicate")); } // onePredicate @@ -377,25 +421,37 @@ public void testOnePredicate() { assertPredicateFalse(PredicateUtils.onePredicate(coll), null); } - @Test(expected=NullPointerException.class) + @Test public void testOnePredicateEx1() { - PredicateUtils.onePredicate((Predicate[]) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.onePredicate((Predicate[]) null); + }); + assertTrue(exception.getMessage().contains("predicate")); } @SuppressWarnings("unchecked") - @Test(expected=NullPointerException.class) + @Test public void testOnePredicateEx2() { - PredicateUtils.onePredicate(new Predicate[] {null}); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.onePredicate(new Predicate[] {null}); + }); + assertTrue(exception.getMessage().contains("predicate")); } - @Test(expected=NullPointerException.class) + @Test public void testOnePredicateEx3() { - PredicateUtils.onePredicate(null, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.onePredicate(null, null); + }); + assertTrue(exception.getMessage().contains("predicate")); } - @Test(expected=NullPointerException.class) + @Test public void testOnePredicateEx4() { - PredicateUtils.onePredicate((Collection>) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.onePredicate((Collection>) null); + }); + assertTrue(exception.getMessage().contains("predicate")); } @SuppressWarnings("unchecked") @@ -404,9 +460,12 @@ public void testOnePredicateEx5() { PredicateUtils.onePredicate(Collections.EMPTY_LIST); } - @Test(expected=NullPointerException.class) + @Test public void testOnePredicateEx6() { - PredicateUtils.onePredicate(Arrays.asList(null, null)); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.onePredicate(Arrays.asList(null, null)); + }); + assertTrue(exception.getMessage().contains("predicate")); } // neitherPredicate @@ -420,9 +479,12 @@ public void testNeitherPredicate() { assertTrue(PredicateUtils.neitherPredicate(FalsePredicate.falsePredicate(), FalsePredicate.falsePredicate()).evaluate(null)); } - @Test(expected=NullPointerException.class) + @Test public void testNeitherPredicateEx() { - PredicateUtils.neitherPredicate(null, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.neitherPredicate(null, null); + }); + assertTrue(exception.getMessage().contains("predicate")); } // nonePredicate @@ -466,26 +528,38 @@ public void testNonePredicate() { assertPredicateTrue(PredicateUtils.nonePredicate(coll), null); } - @Test(expected=NullPointerException.class) + @Test public void testNonePredicateEx1() { - PredicateUtils.nonePredicate((Predicate[]) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.nonePredicate((Predicate[]) null); + }); + assertTrue(exception.getMessage().contains("predicate")); } @SuppressWarnings("unchecked") - @Test(expected=NullPointerException.class) + @Test public void testNonePredicateEx2() { - PredicateUtils.nonePredicate(new Predicate[] {null}); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.nonePredicate(new Predicate[] {null}); + }); + assertTrue(exception.getMessage().contains("predicate")); } @SuppressWarnings("unchecked") - @Test(expected=NullPointerException.class) + @Test public void testNonePredicateEx3() { - PredicateUtils.nonePredicate(null, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.nonePredicate(null, null); + }); + assertTrue(exception.getMessage().contains("predicate")); } - @Test(expected=NullPointerException.class) + @Test public void testNonePredicateEx4() { - PredicateUtils.nonePredicate((Collection>) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.nonePredicate((Collection>) null); + }); + assertTrue(exception.getMessage().contains("predicate")); } @Test @@ -493,12 +567,15 @@ public void testNonePredicateEx5() { PredicateUtils.nonePredicate(Collections.emptyList()); } - @Test(expected=NullPointerException.class) + @Test public void testNonePredicateEx6() { final Collection> coll = new ArrayList<>(); coll.add(null); coll.add(null); - PredicateUtils.nonePredicate(coll); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.nonePredicate(coll); + }); + assertTrue(exception.getMessage().contains("predicate")); } // instanceofPredicate @@ -536,14 +613,20 @@ public void testAsPredicateTransformer() { assertTrue(PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(true)); } - @Test(expected=NullPointerException.class) + @Test public void testAsPredicateTransformerEx1() { - PredicateUtils.asPredicate(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.asPredicate(null); + }); + assertTrue(exception.getMessage().contains("transformer")); } - @Test(expected=FunctorException.class) + @Test public void testAsPredicateTransformerEx2() { - PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(null); + Exception exception = assertThrows(FunctorException.class, () -> { + PredicateUtils.asPredicate(TransformerUtils.nopTransformer()).evaluate(null); + }); + assertTrue(exception.getMessage().contains("Transformer")); } // invokerPredicate @@ -557,19 +640,28 @@ public void testInvokerPredicate() { assertFalse(PredicateUtils.invokerPredicate("isEmpty").evaluate(list)); } - @Test(expected=NullPointerException.class) + @Test public void testInvokerPredicateEx1() { - PredicateUtils.invokerPredicate(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.invokerPredicate(null); + }); + assertTrue(exception.getMessage().contains("methodName")); } - @Test(expected=FunctorException.class) + @Test public void testInvokerPredicateEx2() { - PredicateUtils.invokerPredicate("isEmpty").evaluate(null); + Exception exception = assertThrows(FunctorException.class, () -> { + PredicateUtils.invokerPredicate("isEmpty").evaluate(null); + }); + assertTrue(exception.getMessage().contains("Transformer")); } - @Test(expected=FunctorException.class) + @Test public void testInvokerPredicateEx3() { - PredicateUtils.invokerPredicate("noSuchMethod").evaluate(new Object()); + Exception exception = assertThrows(FunctorException.class, () -> { + PredicateUtils.invokerPredicate("noSuchMethod").evaluate(new Object()); + }); + assertTrue(exception.getMessage().contains("InvokerTransformer")); } // invokerPredicate2 @@ -585,34 +677,49 @@ public void testInvokerPredicate2() { "contains", new Class[]{Object.class}, new Object[]{cString}).evaluate(list)); } - @Test(expected=NullPointerException.class) + @Test public void testInvokerPredicate2Ex1() { - PredicateUtils.invokerPredicate(null, null, null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.invokerPredicate(null, null, null); + }); + assertTrue(exception.getMessage().contains("methodName")); } - @Test(expected=FunctorException.class) + @Test public void testInvokerPredicate2Ex2() { - PredicateUtils.invokerPredicate("contains", new Class[] {Object.class}, new Object[] {cString}).evaluate(null); + Exception exception = assertThrows(FunctorException.class, () -> { + PredicateUtils.invokerPredicate("contains", new Class[] {Object.class}, new Object[] {cString}).evaluate(null); + }); + assertTrue(exception.getMessage().contains("Transformer")); } - @Test(expected=FunctorException.class) + @Test public void testInvokerPredicate2Ex3() { - PredicateUtils.invokerPredicate( - "noSuchMethod", new Class[] {Object.class}, new Object[] {cString}).evaluate(new Object()); + Exception exception = assertThrows(FunctorException.class, () -> { + PredicateUtils.invokerPredicate( + "noSuchMethod", new Class[] {Object.class}, new Object[] {cString}).evaluate(new Object()); + }); + assertTrue(exception.getMessage().contains("InvokerTransformer")); } // nullIsException //------------------------------------------------------------------ - @Test(expected=FunctorException.class) + @Test public void testNullIsExceptionPredicate() { assertTrue(PredicateUtils.nullIsExceptionPredicate(truePredicate()).evaluate(new Object())); - PredicateUtils.nullIsExceptionPredicate(TruePredicate.truePredicate()).evaluate(null); + Exception exception = assertThrows(FunctorException.class, () -> { + PredicateUtils.nullIsExceptionPredicate(TruePredicate.truePredicate()).evaluate(null); + }); + assertTrue(exception.getMessage().contains("Input Object")); } - @Test(expected=NullPointerException.class) + @Test public void testNullIsExceptionPredicateEx1() { - PredicateUtils.nullIsExceptionPredicate(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.nullIsExceptionPredicate(null); + }); + assertTrue(exception.getMessage().contains("predicate")); } // nullIsTrue @@ -625,9 +732,12 @@ public void testNullIsTruePredicate() { assertFalse(PredicateUtils.nullIsTruePredicate(FalsePredicate.falsePredicate()).evaluate(new Object())); } - @Test(expected=NullPointerException.class) + @Test public void testNullIsTruePredicateEx1() { - PredicateUtils.nullIsTruePredicate(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.nullIsTruePredicate(null); + }); + assertTrue(exception.getMessage().contains("predicate")); } // nullIsFalse @@ -640,9 +750,12 @@ public void testNullIsFalsePredicate() { assertFalse(PredicateUtils.nullIsFalsePredicate(FalsePredicate.falsePredicate()).evaluate(new Object())); } - @Test(expected=NullPointerException.class) + @Test public void testNullIsFalsePredicateEx1() { - PredicateUtils.nullIsFalsePredicate(null); + Exception exception = assertThrows(NullPointerException.class, () -> { + PredicateUtils.nullIsFalsePredicate(null); + }); + assertTrue(exception.getMessage().contains("predicate")); } // transformed @@ -660,10 +773,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..8904f5b06a 100644 --- a/src/test/java/org/apache/commons/collections4/QueueUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/QueueUtilsTest.java @@ -16,9 +16,10 @@ */ 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.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.LinkedList; import java.util.Queue; @@ -28,7 +29,7 @@ import org.apache.commons.collections4.queue.SynchronizedQueue; import org.apache.commons.collections4.queue.TransformedQueue; import org.apache.commons.collections4.queue.UnmodifiableQueue; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for QueueUtils factory methods. @@ -44,77 +45,64 @@ 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)); + assertSame(queue, QueueUtils.unmodifiableQueue(queue)); } @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..da826cf58a 100644 --- a/src/test/java/org/apache/commons/collections4/SetUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/SetUtilsTest.java @@ -16,13 +16,13 @@ */ package org.apache.commons.collections4; -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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +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.Arrays; import java.util.Collection; @@ -31,8 +31,8 @@ import org.apache.commons.collections4.SetUtils.SetView; import org.apache.commons.collections4.set.PredicatedSet; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for SetUtils. @@ -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,22 +108,18 @@ 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 + @BeforeEach public void setUp() { setA = new HashSet<>(); setA.add(1); @@ -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)); + assertEquals(3, set2.size()); + 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")); + assertEquals(3, set3.size()); + 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)); + assertEquals(1, set4.size()); + 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)); + assertEquals(3, set2.size()); + 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")); + assertEquals(3, set3.size()); + 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)); + assertEquals(1, set4.size()); + 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..405d8e8b6d 100644 --- a/src/test/java/org/apache/commons/collections4/SplitMapUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/SplitMapUtilsTest.java @@ -16,11 +16,12 @@ */ package org.apache.commons.collections4; -import static org.junit.Assert.assertEquals; -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.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.HashMap; import java.util.Map; @@ -28,8 +29,8 @@ import org.apache.commons.collections4.functors.NOPTransformer; import org.apache.commons.collections4.map.HashedMap; import org.apache.commons.collections4.splitmap.TransformedSplitMap; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests for {@link TransformedSplitMap} @@ -43,7 +44,7 @@ public class SplitMapUtilsTest { private final Transformer stringToInt = Integer::valueOf; - @Before + @BeforeEach public void setUp() throws Exception { backingMap = new HashMap<>(); transformedMap = TransformedSplitMap.transformingMap(backingMap, NOPTransformer.nopTransformer(), @@ -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/TestUtils.java b/src/test/java/org/apache/commons/collections4/TestUtils.java index 00a7d9f829..c5c4757242 100644 --- a/src/test/java/org/apache/commons/collections4/TestUtils.java +++ b/src/test/java/org/apache/commons/collections4/TestUtils.java @@ -16,7 +16,7 @@ */ package org.apache.commons.collections4; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -57,7 +57,7 @@ public static void assertSameAfterSerialization(final String msg, final Object o ois.close(); // assert that original object and deserialized objects are the same - assertSame(msg, o, object); + assertSame(o, object); } catch (final IOException e) { // should never happen throw new RuntimeException(e); diff --git a/src/test/java/org/apache/commons/collections4/TransformerUtilsTest.java b/src/test/java/org/apache/commons/collections4/TransformerUtilsTest.java index 1c21fdd43d..d37ebda722 100644 --- a/src/test/java/org/apache/commons/collections4/TransformerUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/TransformerUtilsTest.java @@ -16,11 +16,12 @@ */ package org.apache.commons.collections4; -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.assertEquals; +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.Collection; @@ -37,7 +38,7 @@ import org.apache.commons.collections4.functors.NOPTransformer; import org.apache.commons.collections4.functors.StringValueTransformer; import org.apache.commons.collections4.functors.TruePredicate; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the TransformerUtils class. @@ -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 @@ -434,12 +441,9 @@ public void testInvokerTransformer2() { @Test public void testStringValueTransformer() { - assertNotNull( "StringValueTransformer should NEVER return a null value.", - TransformerUtils.stringValueTransformer().transform(null)); - assertEquals( "StringValueTransformer should return \"null\" when given a null argument.", "null", - TransformerUtils.stringValueTransformer().transform(null)); - assertEquals( "StringValueTransformer should return toString value", "6", - TransformerUtils.stringValueTransformer().transform(6)); + assertNotNull(TransformerUtils.stringValueTransformer().transform(null)); + assertEquals("null", TransformerUtils.stringValueTransformer().transform(null)); + assertEquals("6", TransformerUtils.stringValueTransformer().transform(6)); } // instantiateFactory @@ -447,22 +451,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..a79b72cb1a 100644 --- a/src/test/java/org/apache/commons/collections4/TrieUtilsTest.java +++ b/src/test/java/org/apache/commons/collections4/TrieUtilsTest.java @@ -16,11 +16,13 @@ */ package org.apache.commons.collections4; -import static org.junit.Assert.*; +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.apache.commons.collections4.trie.PatriciaTrie; import org.apache.commons.collections4.trie.UnmodifiableTrie; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for TrieUtils factory methods. @@ -33,18 +35,14 @@ 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 - } + }); + assertTrue(exception.getMessage().contains("trie")); - assertSame("UnmodifiableTrie shall not be decorated", trie, TrieUtils.unmodifiableTrie(trie)); + assertSame(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 c8e696279e..bfab276882 100644 --- a/src/test/java/org/apache/commons/collections4/bag/AbstractBagTest.java +++ b/src/test/java/org/apache/commons/collections4/bag/AbstractBagTest.java @@ -33,7 +33,10 @@ import org.apache.commons.collections4.collection.AbstractCollectionTest; import org.apache.commons.collections4.set.AbstractSetTest; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.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..0da40834df 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,32 @@ 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()) { + 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()) { + 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 +89,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 +104,18 @@ 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()) { + assertTrue(exception.getMessage().contains("key")); + } } else { - assertEquals(null, bidi.nextKey(null)); + assertNull(bidiMap.nextKey(null)); } } @@ -114,10 +125,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 +142,18 @@ 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()) { + 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/bloomfilter/AbstractBloomFilterTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/AbstractBloomFilterTest.java index b37a5a9e5c..58c1d5d8d2 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/AbstractBloomFilterTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/AbstractBloomFilterTest.java @@ -16,10 +16,11 @@ */ package org.apache.commons.collections4.bloomfilter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.List; import java.util.PrimitiveIterator.OfInt; @@ -33,7 +34,7 @@ import org.apache.commons.collections4.bloomfilter.hasher.Hasher; import org.apache.commons.collections4.bloomfilter.hasher.Shape; import org.apache.commons.collections4.bloomfilter.hasher.StaticHasher; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test standard methods in the {@link BloomFilter} interface. @@ -207,10 +208,10 @@ private void assertSameBits(final StaticHasher hasher1, final StaticHasher hashe final OfInt iter2 = hasher2.iterator(shape); while (iter1.hasNext()) { - assertTrue("Not enough data in second hasher", iter2.hasNext()); + assertTrue(iter2.hasNext()); assertEquals(iter1.nextInt(), iter2.nextInt()); } - assertFalse("Too much data in second hasher", iter2.hasNext()); + assertFalse(iter2.hasNext()); } /** @@ -261,12 +262,10 @@ public final void constructorTest_WrongShape() { final List lst = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); final Hasher hasher = new StaticHasher(lst.iterator(), anotherShape); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { createFilter(hasher, shape); - fail("Should throw IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing. - } + }); + assertNotNull(exception.getMessage()); } /** @@ -297,12 +296,10 @@ public final void containsTest_BloomFilter_WrongShape() { final Shape anotherShape = new Shape(testFunctionX, 3, 72, 17); final Hasher hasher2 = new StaticHasher(lst.iterator(), anotherShape); final BloomFilter bf2 = createFilter(hasher2, anotherShape); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { bf.contains(bf2); - fail("Should throw IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing. - } + }); + assertNotNull(exception.getMessage()); } /** @@ -340,12 +337,10 @@ public final void containsTest_Hasher_WrongShape() { final List lst2 = Arrays.asList(4, 5, 6, 7, 8, 9, 10); final Hasher hasher2 = new StaticHasher(lst2.iterator(), anotherShape); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { bf.contains(hasher2); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing - } + }); + assertNotNull(exception.getMessage()); } /** @@ -466,7 +461,7 @@ private void mergeTest_BloomFilter(BiFunction filter final BloomFilter bf2 = filterFactory.apply(hasher2, shape); - assertTrue("Merge should not fail", bf.merge(bf2)); + assertTrue(bf.merge(bf2)); assertEquals(27, bf.cardinality()); } @@ -485,12 +480,10 @@ public final void mergeTest_BloomFilter_WrongShape() { final Hasher hasher2 = new StaticHasher(lst2.iterator(), anotherShape); final BloomFilter bf2 = createFilter(hasher2, anotherShape); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { bf.merge(bf2); - fail("Should throw IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing. - } + }); + assertNotNull(exception.getMessage()); } /** @@ -506,7 +499,7 @@ public final void mergeTest_Hasher() { final List lst2 = Arrays.asList(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27); final Hasher hasher2 = new StaticHasher(lst2.iterator(), shape); - assertTrue("Merge should not fail", bf.merge(hasher2)); + assertTrue(bf.merge(hasher2)); assertEquals(27, bf.cardinality()); } @@ -524,12 +517,10 @@ public final void mergeTest_Hasher_WrongShape() { final List lst2 = Arrays.asList(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27); final Hasher hasher2 = new StaticHasher(lst2.iterator(), anotherShape); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { bf.merge(hasher2); - fail("Should throw IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing. - } + }); + assertNotNull(exception.getMessage()); } /** diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/ArrayCountingBloomFilterTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/ArrayCountingBloomFilterTest.java index 7bd5e5d503..9ec36a990e 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/ArrayCountingBloomFilterTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/ArrayCountingBloomFilterTest.java @@ -16,9 +16,9 @@ */ package org.apache.commons.collections4.bloomfilter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.HashMap; @@ -30,7 +30,7 @@ import org.apache.commons.collections4.bloomfilter.hasher.Hasher; import org.apache.commons.collections4.bloomfilter.hasher.Shape; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for the {@link ArrayCountingBloomFilter}. @@ -75,10 +75,10 @@ private static void assertCounts(CountingBloomFilter bf, int[] expected) { int zeros = 0; for (int i = 0; i < expected.length; i++) { if (m.get(i) == null) { - assertEquals("Wrong value for " + i, expected[i], 0); + assertEquals(expected[i], 0); zeros++; } else { - assertEquals("Wrong value for " + i, expected[i], m.get(i).intValue()); + assertEquals(expected[i], m.get(i).intValue()); } } assertEquals(expected.length - zeros, bf.cardinality()); @@ -286,7 +286,7 @@ public void mergeTest_Overflow() { // Big + 1 = Overflow assertTrue(bf2.isValid()); assertFalse(bf2.merge(bf)); - assertFalse("Merge should overflow and the filter is invalid", bf2.isValid()); + assertFalse(bf2.isValid()); // The counts are not clipped to max. They have simply overflowed. // Note that this is a merge and the count is only incremented by 1 @@ -313,7 +313,7 @@ public void removeTest_Negative() { // Less - More = Negative assertTrue(bf2.isValid()); bf2.remove(bf); - assertFalse("Remove should create negative counts and the filter is invalid", bf2.isValid()); + assertFalse(bf2.isValid()); // The counts are not clipped to zero. They have been left as negative. assertCounts(bf2, new int[] {0, -1, 1, -1}); diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/BloomFilterIndexerTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/BloomFilterIndexerTest.java index 5c063ffa00..8159deb113 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/BloomFilterIndexerTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/BloomFilterIndexerTest.java @@ -16,8 +16,11 @@ */ package org.apache.commons.collections4.bloomfilter; -import org.junit.Assert; -import org.junit.Test; +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 org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Random; @@ -28,40 +31,43 @@ */ public class BloomFilterIndexerTest { - @Test(expected = IndexOutOfBoundsException.class) + @Test public void testCheckPositiveThrows() { - BloomFilterIndexer.checkPositive(-1); + Exception exception = assertThrows(IndexOutOfBoundsException.class, () -> { + BloomFilterIndexer.checkPositive(-1); + }); + assertTrue(exception.getMessage().contains("Negative bitIndex: -1")); } @Test public void testGetLongIndex() { - Assert.assertEquals(0, BloomFilterIndexer.getLongIndex(0)); + assertEquals(0, BloomFilterIndexer.getLongIndex(0)); for (final int index : getIndexes()) { // getLongIndex is expected to identify a block of 64-bits (starting from zero) - Assert.assertEquals(index / Long.SIZE, BloomFilterIndexer.getLongIndex(index)); + assertEquals(index / Long.SIZE, BloomFilterIndexer.getLongIndex(index)); // Verify the behavior for negatives. It should produce a negative (invalid) // as a simple trip for incorrect usage. - Assert.assertTrue(BloomFilterIndexer.getLongIndex(-index) < 0); + assertTrue(BloomFilterIndexer.getLongIndex(-index) < 0); // If index is not zero then when negated this is what a signed shift // of 6-bits actually does - Assert.assertEquals(((1 - index) / Long.SIZE) - 1, + assertEquals(((1 - index) / Long.SIZE) - 1, BloomFilterIndexer.getLongIndex(-index)); } } @Test public void testGetLongBit() { - Assert.assertEquals(1L, BloomFilterIndexer.getLongBit(0)); + assertEquals(1L, BloomFilterIndexer.getLongBit(0)); for (final int index : getIndexes()) { // getLongBit is expected to identify a single bit in a 64-bit block - Assert.assertEquals(1L << (index % Long.SIZE), BloomFilterIndexer.getLongBit(index)); + assertEquals(1L << (index % Long.SIZE), BloomFilterIndexer.getLongBit(index)); // Verify the behavior for negatives - Assert.assertEquals(1L << (64 - (index & 0x3f)), BloomFilterIndexer.getLongBit(-index)); + assertEquals(1L << (64 - (index & 0x3f)), BloomFilterIndexer.getLongBit(-index)); } } diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/HasherBloomFilterTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/HasherBloomFilterTest.java index e9b63bac1e..32bc3409a4 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/HasherBloomFilterTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/HasherBloomFilterTest.java @@ -16,15 +16,15 @@ */ package org.apache.commons.collections4.bloomfilter; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.collections4.bloomfilter.hasher.DynamicHasher; import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity; import org.apache.commons.collections4.bloomfilter.hasher.Hasher; import org.apache.commons.collections4.bloomfilter.hasher.Shape; import org.apache.commons.collections4.bloomfilter.hasher.function.MD5Cyclic; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.PrimitiveIterator.OfInt; @@ -65,7 +65,7 @@ protected HasherBloomFilter createFilter(final Hasher hasher, final Shape shape) @Test public void getBitsTest_Empty() { BloomFilter filter = createEmptyFilter(shape); - Assert.assertArrayEquals(new long[0], filter.getBits()); + assertArrayEquals(new long[0], filter.getBits()); } /** @@ -87,6 +87,6 @@ public HashFunctionIdentity getHashFunctionIdentity() { return shape.getHashFunctionIdentity(); } }); - Assert.assertArrayEquals(new long[] {1L}, filter.getBits()); + assertArrayEquals(new long[] {1L}, filter.getBits()); } } diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/IndexFilterTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/IndexFilterTest.java index ad008ba01a..02732ff69b 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/IndexFilterTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/IndexFilterTest.java @@ -16,12 +16,15 @@ */ package org.apache.commons.collections4.bloomfilter; +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 org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentityImpl; import org.apache.commons.collections4.bloomfilter.hasher.Shape; import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity.ProcessType; import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity.Signedness; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -50,26 +53,20 @@ public void testApplyThrowsWithNullArguments() { final ArrayList actual = new ArrayList<>(); final IntConsumer consumer = actual::add; - try { + Exception exception = assertThrows(NullPointerException.class, () -> { IndexFilters.distinctIndexes(null, shape, consumer); - Assert.fail("null hasher"); - } catch (NullPointerException expected) { - // Ignore - } + }); + assertTrue(exception.getMessage().contains("hasher")); - try { + exception = assertThrows(NullPointerException.class, () -> { IndexFilters.distinctIndexes(hasher, null, consumer); - Assert.fail("null shape"); - } catch (NullPointerException expected) { - // Ignore - } + }); + assertTrue(exception.getMessage().contains("shape")); - try { + exception = assertThrows(NullPointerException.class, () -> { IndexFilters.distinctIndexes(hasher, shape, null); - Assert.fail("null consumer"); - } catch (NullPointerException expected) { - // Ignore - } + }); + assertTrue(exception.getMessage().contains("consumer")); // All OK together IndexFilters.distinctIndexes(hasher, shape, consumer); @@ -92,12 +89,12 @@ private void assertFilter(int... indexes) { IndexFilters.distinctIndexes(hasher, shape, actual::add); - Assert.assertEquals(expected.size(), actual.size()); + assertEquals(expected.size(), actual.size()); // Check the array has all the values. // We do not currently check the order of indexes from the // hasher.iterator() function. for (Integer index : actual) { - Assert.assertTrue(expected.contains(index)); + assertTrue(expected.contains(index)); } } } diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/SetOperationsTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/SetOperationsTest.java index 0d2d53a443..ccc45e62c4 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/SetOperationsTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/SetOperationsTest.java @@ -16,15 +16,17 @@ */ package org.apache.commons.collections4.bloomfilter; -import static org.junit.Assert.assertEquals; +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 java.util.List; import java.util.Arrays; import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity; import org.apache.commons.collections4.bloomfilter.hasher.Hasher; import org.apache.commons.collections4.bloomfilter.hasher.Shape; import org.apache.commons.collections4.bloomfilter.hasher.StaticHasher; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test {@link SetOperations}. @@ -72,12 +74,10 @@ public void testDifferentShapesThrows() { Hasher hasher2 = new StaticHasher(lst2.iterator(), shape2); BloomFilter filter2 = new HasherBloomFilter(hasher2, shape2); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { SetOperations.cosineDistance(filter1, filter2); - Assert.fail("Expected an IllegalArgumentException"); - } catch (IllegalArgumentException expected) { - // Ignore - } + }); + assertNotNull(exception.getMessage()); } /** @@ -93,8 +93,8 @@ public final void cosineDistanceTest() { Hasher hasher2 = new StaticHasher(lst2.iterator(), shape); BloomFilter filter2 = new HasherBloomFilter(hasher2, shape); - assertEquals(0.5, SetOperations.cosineDistance(filter1, filter2), 0.0001); - assertEquals(0.5, SetOperations.cosineDistance(filter2, filter1), 0.0001); + assertEquals(SetOperations.cosineDistance(filter1, filter2), 0.5000000000000001); + assertEquals(SetOperations.cosineDistance(filter2, filter1), 0.5000000000000001); lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17); hasher = new StaticHasher(lst.iterator(), shape); @@ -104,15 +104,15 @@ public final void cosineDistanceTest() { hasher2 = new StaticHasher(lst2.iterator(), shape); filter2 = new HasherBloomFilter(hasher2, shape); - assertEquals(0.0, SetOperations.cosineDistance(filter1, filter2), 0.0001); - assertEquals(0.0, SetOperations.cosineDistance(filter2, filter1), 0.0001); + assertEquals(SetOperations.cosineDistance(filter1, filter2), 0.0); + assertEquals(SetOperations.cosineDistance(filter2, filter1), 0.0); lst2 = Arrays.asList(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25); hasher2 = new StaticHasher(lst2.iterator(), shape); filter2 = new HasherBloomFilter(hasher2, shape); - assertEquals(0.514928749927334, SetOperations.cosineDistance(filter1, filter2), 0.000000000000001); - assertEquals(0.514928749927334, SetOperations.cosineDistance(filter2, filter1), 0.000000000000001); + assertEquals(SetOperations.cosineDistance(filter1, filter2), 0.5149287499273341); + assertEquals(SetOperations.cosineDistance(filter2, filter1), 0.5149287499273341); } /** @@ -128,10 +128,10 @@ public final void cosineDistanceTest_NoValues() { final Hasher hasher = new StaticHasher(lst.iterator(), shape); final BloomFilter filter3 = new HasherBloomFilter(hasher, shape); - assertEquals(1.0, SetOperations.cosineDistance(filter1, filter2), 0.0001); - assertEquals(1.0, SetOperations.cosineDistance(filter2, filter1), 0.0001); - assertEquals(1.0, SetOperations.cosineDistance(filter1, filter3), 0.0001); - assertEquals(1.0, SetOperations.cosineDistance(filter3, filter1), 0.0001); + assertEquals(SetOperations.cosineDistance(filter1, filter2), 1.0); + assertEquals(SetOperations.cosineDistance(filter2, filter1), 1.0); + assertEquals(SetOperations.cosineDistance(filter1, filter3), 1.0); + assertEquals(SetOperations.cosineDistance(filter3, filter1), 1.0); } /** @@ -154,8 +154,8 @@ public final void cosineSimilarityTest() { hasher2 = new StaticHasher(lst2.iterator(), shape); filter2 = new HasherBloomFilter(hasher2, shape); - assertEquals(0.485071250072666, SetOperations.cosineSimilarity(filter1, filter2), 0.000000000000001); - assertEquals(0.485071250072666, SetOperations.cosineSimilarity(filter2, filter1), 0.000000000000001); + assertEquals(SetOperations.cosineSimilarity(filter1, filter2), 0.48507125007266594); + assertEquals(SetOperations.cosineSimilarity(filter2, filter1), 0.48507125007266594); } /** @@ -171,10 +171,10 @@ public final void cosineSimilarityTest_NoValues() { final Hasher hasher = new StaticHasher(lst.iterator(), shape); final BloomFilter filter3 = new HasherBloomFilter(hasher, shape); - assertEquals(0.0, SetOperations.cosineSimilarity(filter1, filter2), 0.0001); - assertEquals(0.0, SetOperations.cosineSimilarity(filter2, filter1), 0.0001); - assertEquals(0.0, SetOperations.cosineSimilarity(filter1, filter3), 0.0001); - assertEquals(0.0, SetOperations.cosineSimilarity(filter3, filter1), 0.0001); + assertEquals(SetOperations.cosineSimilarity(filter1, filter2), 0.0); + assertEquals(SetOperations.cosineSimilarity(filter2, filter1), 0.0); + assertEquals(SetOperations.cosineSimilarity(filter1, filter3), 0.0); + assertEquals(SetOperations.cosineSimilarity(filter3, filter1), 0.0); } /** @@ -278,15 +278,15 @@ public final void jaccardDistanceTest() { Hasher hasher2 = new StaticHasher(lst2.iterator(), shape); BloomFilter filter2 = new HasherBloomFilter(hasher2, shape); - assertEquals(1.0, SetOperations.jaccardDistance(filter1, filter2), 0.0001); - assertEquals(1.0, SetOperations.jaccardDistance(filter2, filter1), 0.0001); + assertEquals(SetOperations.jaccardDistance(filter1, filter2), 1.0); + assertEquals(SetOperations.jaccardDistance(filter2, filter1), 1.0); lst2 = Arrays.asList(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25); hasher2 = new StaticHasher(lst2.iterator(), shape); filter2 = new HasherBloomFilter(hasher2, shape); - assertEquals(0.32, SetOperations.jaccardDistance(filter1, filter2), 0.001); - assertEquals(0.32, SetOperations.jaccardDistance(filter2, filter1), 0.001); + assertEquals(SetOperations.jaccardDistance(filter1, filter2), 0.31999999999999995); + assertEquals(SetOperations.jaccardDistance(filter2, filter1), 0.31999999999999995); } /** @@ -302,10 +302,10 @@ public final void jaccardDistanceTest_NoValues() { final Hasher hasher = new StaticHasher(lst.iterator(), shape); final BloomFilter filter3 = new HasherBloomFilter(hasher, shape); - assertEquals(1.0, SetOperations.jaccardDistance(filter1, filter2), 0.0001); - assertEquals(1.0, SetOperations.jaccardDistance(filter2, filter1), 0.0001); - assertEquals(0.0, SetOperations.jaccardDistance(filter1, filter3), 0.0001); - assertEquals(0.0, SetOperations.jaccardDistance(filter3, filter1), 0.0001); + assertEquals(SetOperations.jaccardDistance(filter1, filter2), 1.0); + assertEquals(SetOperations.jaccardDistance(filter2, filter1), 1.0); + assertEquals(SetOperations.jaccardDistance(filter1, filter3), 0.0); + assertEquals(SetOperations.jaccardDistance(filter3, filter1), 0.0); } /** @@ -321,15 +321,15 @@ public final void jaccardSimilarityTest() { Hasher hasher2 = new StaticHasher(lst2.iterator(), shape); BloomFilter filter2 = new HasherBloomFilter(hasher2, shape); - assertEquals(0.0, SetOperations.jaccardSimilarity(filter1, filter2), 0.0001); - assertEquals(0.0, SetOperations.jaccardSimilarity(filter2, filter1), 0.0001); + assertEquals(SetOperations.jaccardSimilarity(filter1, filter2), 0.0); + assertEquals(SetOperations.jaccardSimilarity(filter2, filter1), 0.0); lst2 = Arrays.asList(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25); hasher2 = new StaticHasher(lst2.iterator(), shape); filter2 = new HasherBloomFilter(hasher2, shape); - assertEquals(0.68, SetOperations.jaccardSimilarity(filter1, filter2), 0.001); - assertEquals(0.68, SetOperations.jaccardSimilarity(filter2, filter1), 0.001); + assertEquals(SetOperations.jaccardSimilarity(filter1, filter2), 0.68); + assertEquals(SetOperations.jaccardSimilarity(filter2, filter1), 0.68); } /** @@ -345,9 +345,9 @@ public final void jaccardSimilarityTest_NoValues() { final Hasher hasher = new StaticHasher(lst.iterator(), shape); final BloomFilter filter3 = new HasherBloomFilter(hasher, shape); - assertEquals(0.0, SetOperations.jaccardSimilarity(filter1, filter2), 0.0001); - assertEquals(0.0, SetOperations.jaccardSimilarity(filter2, filter1), 0.0001); - assertEquals(1.0, SetOperations.jaccardSimilarity(filter1, filter3), 0.0001); - assertEquals(1.0, SetOperations.jaccardSimilarity(filter3, filter1), 0.0001); + assertEquals(SetOperations.jaccardSimilarity(filter1, filter2), 0.0); + assertEquals(SetOperations.jaccardSimilarity(filter2, filter1), 0.0); + assertEquals(SetOperations.jaccardSimilarity(filter1, filter3), 1.0); + assertEquals(SetOperations.jaccardSimilarity(filter3, filter1), 1.0); } } diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/DynamicHasherBuilderTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/DynamicHasherBuilderTest.java index 4f14bea4b3..b30b126082 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/DynamicHasherBuilderTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/DynamicHasherBuilderTest.java @@ -16,18 +16,19 @@ */ package org.apache.commons.collections4.bloomfilter.hasher; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.nio.charset.StandardCharsets; import java.util.NoSuchElementException; import java.util.PrimitiveIterator.OfInt; import org.apache.commons.collections4.bloomfilter.hasher.function.MD5Cyclic; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * {@link DynamicHasher.Builder} tests. @@ -65,12 +66,10 @@ public void buildTest_Empty() { final OfInt iter = hasher.iterator(shape); assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.nextInt(); - fail("Should have thrown NoSuchElementException"); - } catch (final NoSuchElementException ignore) { - // do nothing - } + }); + assertNull(exception.getMessage()); } /** @@ -125,7 +124,7 @@ public void buildResetTest() { /** * Sets up the builder for testing. */ - @Before + @BeforeEach public void setup() { builder = new DynamicHasher.Builder(hf); } diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/DynamicHasherTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/DynamicHasherTest.java index 317bf95d27..3b1b34efb9 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/DynamicHasherTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/DynamicHasherTest.java @@ -16,18 +16,20 @@ */ package org.apache.commons.collections4.bloomfilter.hasher; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.nio.charset.StandardCharsets; import java.util.NoSuchElementException; import java.util.PrimitiveIterator.OfInt; import org.apache.commons.collections4.bloomfilter.hasher.function.MD5Cyclic; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests the {@link DynamicHasher}. @@ -67,7 +69,7 @@ public Signedness getSignedness() { /** * Sets up the DynamicHasher. */ - @Before + @BeforeEach public void setup() { builder = new DynamicHasher.Builder(new MD5Cyclic()); shape = new Shape(new MD5Cyclic(), 3, 72, 17); @@ -109,12 +111,10 @@ public void testGetBits_MultipleHashes() { assertEquals(element, iter.nextInt()); } assertFalse(iter.hasNext()); - try { + Exception exception = assertThrows(NoSuchElementException.class, () -> { iter.next(); - fail("Should have thrown NoSuchElementException"); - } catch (final NoSuchElementException ignore) { - // do nothing - } + }); + assertNull(exception.getMessage()); } /** @@ -125,11 +125,9 @@ public void testGetBits_WrongShape() { final Hasher hasher = builder.with("Hello", StandardCharsets.UTF_8).build(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { hasher.iterator(new Shape(testFunction, 3, 72, 17)); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing - } + }); + assertNotNull(exception.getMessage()); } } diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionIdentityImplTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionIdentityImplTest.java index 3a125bd792..479cfa5188 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionIdentityImplTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionIdentityImplTest.java @@ -16,11 +16,11 @@ */ package org.apache.commons.collections4.bloomfilter.hasher; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity.Signedness; import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity.ProcessType; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the HashFunctionIdentity implementation ({@link HashFunctionIdentityImpl}).. diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionValidatorTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionValidatorTest.java index 625cb645ec..75b78a3cff 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionValidatorTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HashFunctionValidatorTest.java @@ -16,12 +16,13 @@ */ package org.apache.commons.collections4.bloomfilter.hasher; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +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 org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity.ProcessType; import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity.Signedness; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests of the {@link HashFunctionValidator}. @@ -108,12 +109,15 @@ public void testSignedness() { /** * Test the check method throws when the two hash functions are not equal. */ - @Test(expected=IllegalArgumentException.class) + @Test public void testCheckThrows() { final HashFunctionIdentityImpl impl1 = new HashFunctionIdentityImpl("Testing Suite", "impl1", Signedness.SIGNED, ProcessType.CYCLIC, 300L); final HashFunctionIdentityImpl impl2 = new HashFunctionIdentityImpl("Testing Suite", "impl1", Signedness.UNSIGNED, ProcessType.CYCLIC, 300L); - HashFunctionValidator.checkAreEqual(impl1, impl2); + Exception exception = assertThrows(IllegalArgumentException.class, () -> { + HashFunctionValidator.checkAreEqual(impl1, impl2); + }); + assertTrue(exception.getMessage().contains("Hash functions are not equal")); } } diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HasherBuilderTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HasherBuilderTest.java index 0216075ad5..26b5396dd8 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HasherBuilderTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/HasherBuilderTest.java @@ -16,10 +16,12 @@ */ package org.apache.commons.collections4.bloomfilter.hasher; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + import org.apache.commons.collections4.bloomfilter.hasher.Hasher.Builder; import org.apache.commons.lang3.NotImplementedException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; @@ -64,7 +66,7 @@ public void withCharSequenceTest() { }) { TestBuilder builder = new TestBuilder(); builder.with(s, cs); - Assert.assertArrayEquals(s.getBytes(cs), builder.items.get(0)); + assertArrayEquals(s.getBytes(cs), builder.items.get(0)); } } } @@ -82,12 +84,12 @@ public void withUnencodedCharSequenceTest() { final byte[] encoded = builder.items.get(0); final char[] original = s.toCharArray(); // Should be twice the length - Assert.assertEquals(original.length * 2, encoded.length); + assertEquals(original.length * 2, encoded.length); // Should be little endian (lower bits first) final CharBuffer buffer = ByteBuffer.wrap(encoded) .order(ByteOrder.LITTLE_ENDIAN).asCharBuffer(); for (int i = 0; i < original.length; i++) { - Assert.assertEquals(original[i], buffer.get(i)); + assertEquals(original[i], buffer.get(i)); } } } diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/ShapeTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/ShapeTest.java index 35edb1a87a..f8c7976039 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/ShapeTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/ShapeTest.java @@ -16,16 +16,18 @@ */ package org.apache.commons.collections4.bloomfilter.hasher; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +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 org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity.ProcessType; import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity.Signedness; import java.util.ArrayList; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the {@link Shape} class. @@ -79,12 +81,10 @@ public Signedness getSignedness() { */ @Test public void constructor_items_bits_BadNumberOfBitsTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 5, 0); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Number of bits must be greater than 0: 0")); } /** @@ -92,12 +92,10 @@ public void constructor_items_bits_BadNumberOfBitsTest() { */ @Test public void constructor_items_bits_BadNumberOfHashFunctionsTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 16, 8); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Filter too small: Calculated number of hash functions (0) was less than 1")); } /** @@ -105,12 +103,10 @@ public void constructor_items_bits_BadNumberOfHashFunctionsTest() { */ @Test public void constructor_items_bits_BadNumberOfItemsTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 0, 24); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Number of items must be greater than 0: 0")); } /** @@ -118,12 +114,10 @@ public void constructor_items_bits_BadNumberOfItemsTest() { */ @Test public void constructor_items_bits_hash_BadNumberOfBitsTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 5, 0, 1); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Number of bits must be greater than 0: 0")); } /** @@ -131,12 +125,10 @@ public void constructor_items_bits_hash_BadNumberOfBitsTest() { */ @Test public void constructor_items_bits_hash_BadNumberOfHashFunctionsTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 5, 24, 0); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Number of hash functions must be greater than 0: 0")); } /** @@ -144,12 +136,10 @@ public void constructor_items_bits_hash_BadNumberOfHashFunctionsTest() { */ @Test public void constructor_items_bits_hash_BadNumberOfItemsTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 0, 24, 1); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Number of items must be greater than 0: 0")); } /** @@ -157,12 +147,10 @@ public void constructor_items_bits_hash_BadNumberOfItemsTest() { */ @Test public void constructor_items_bits_hash_BadProbabilityTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 4000, 8, 1); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Calculated probability is greater than or equal to 1: 1.0")); } /** @@ -203,12 +191,10 @@ public void constructor_items_bitsTest() { */ @Test public void constructor_items_probability_BadNumberOfItemsTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 0, 1.0 / 10); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing. - } + }); + assertTrue(exception.getMessage().contains("Number of items must be greater than 0: 0")); } /** @@ -216,23 +202,21 @@ public void constructor_items_probability_BadNumberOfItemsTest() { */ @Test public void constructor_items_probability_BadProbabilityTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 10, 0.0); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing. - } - try { + }); + assertTrue(exception.getMessage().contains("Probability must be greater than 0 and less than 1: 0.0")); + exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 10, 1.0); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing. + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } - try { + exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 10, Double.NaN); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing. + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } @@ -241,12 +225,10 @@ public void constructor_items_probability_BadProbabilityTest() { */ @Test public void constructor_items_probability_NumberOfBitsOverflowTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, Integer.MAX_VALUE, 1.0 / 10); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing. - } + }); + assertTrue(exception.getMessage().contains("Resulting filter has more than 2147483647 bits:")); } /** @@ -266,12 +248,10 @@ public void constructor_items_probability_Test() { */ @Test public void constructor_nm_noName() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { new Shape(null, 5, 72); - fail("Should throw NullPointerException"); - } catch (final NullPointerException expected) { - // do nothing - } + }); + assertTrue(exception.getMessage().contains("hashFunctionIdentity")); } /** @@ -279,12 +259,10 @@ public void constructor_nm_noName() { */ @Test public void constructor_nmk_noName() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { new Shape(null, 5, 72, 17); - fail("Should throw NullPointerException"); - } catch (final NullPointerException expected) { - // do nothing - } + }); + assertTrue(exception.getMessage().contains("hashFunctionIdentity")); } /** @@ -292,12 +270,10 @@ public void constructor_nmk_noName() { */ @Test public void constructor_np_noName() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { new Shape(null, 5, 0.1); - fail("Should throw NullPointerException"); - } catch (final NullPointerException expected) { - // do nothing - } + }); + assertTrue(exception.getMessage().contains("hashFunctionIdentity")); } /** @@ -305,12 +281,10 @@ public void constructor_np_noName() { */ @Test public void constructor_pmk_noName() { - try { + Exception exception = assertThrows(NullPointerException.class, () -> { new Shape(null, 0.1, 72, 17); - fail("Should throw NullPointerException"); - } catch (final NullPointerException expected) { - // do nothing - } + }); + assertTrue(exception.getMessage().contains("hashFunctionIdentity")); } /** @@ -318,12 +292,10 @@ public void constructor_pmk_noName() { */ @Test public void constructor_probability_bits_hash_BadNumberOfBitsTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 0.5, 0, 1); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Number of bits must be greater than 0: 0")); } /** @@ -331,12 +303,10 @@ public void constructor_probability_bits_hash_BadNumberOfBitsTest() { */ @Test public void constructor_probability_bits_hash_BadNumberOfHashFunctionsTest() { - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 0.5, 24, 0); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Number of hash functions must be greater than 0: 0")); } /** @@ -345,43 +315,39 @@ public void constructor_probability_bits_hash_BadNumberOfHashFunctionsTest() { @Test public void constructor_probability_bits_hash_BadProbabilityTest() { // probability should not be 0 - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 0.0, 24, 1); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Probability must be greater than 0 and less than 1: 0.0")); // probability should not be = -1 - try { + exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, -1.0, 24, 1); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected - } + }); + assertTrue(exception.getMessage().contains("Probability must be greater than 0 and less than 1: -1.0")); // probability should not be < -1 - try { + exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, -1.5, 24, 1); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } // probability should not be = 1 - try { + exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 1.0, 24, 1); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } // probability should not be > 1 - try { + exception = assertThrows(IllegalArgumentException.class, () -> { new Shape(testFunction, 2.0, 24, 1); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // expected + }); + if (null != exception.getMessage()) { + assertNotNull(exception.getMessage()); } } diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/StaticHasherTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/StaticHasherTest.java index f2718cfe5a..074eaf55cd 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/StaticHasherTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/StaticHasherTest.java @@ -16,17 +16,18 @@ */ package org.apache.commons.collections4.bloomfilter.hasher; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Arrays; import java.util.Iterator; import java.util.List; import java.util.PrimitiveIterator.OfInt; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the {@link StaticHasher}. @@ -102,10 +103,10 @@ private void assertSameBits(final StaticHasher hasher1, final StaticHasher hashe final OfInt iter2 = hasher2.iterator(shape); while (iter1.hasNext()) { - assertTrue("Not enough data in second hasher", iter2.hasNext()); + assertTrue(iter2.hasNext()); assertEquals(iter1.nextInt(), iter2.nextInt()); } - assertFalse("Too much data in second hasher", iter2.hasNext()); + assertFalse(iter2.hasNext()); } /** @@ -159,12 +160,10 @@ public HashFunctionIdentity getHashFunctionIdentity() { } }; - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new StaticHasher(testHasher, shape); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing - } + }); + assertNotNull(exception.getMessage()); } /** @@ -188,7 +187,7 @@ public void testConstructor_Iterator() { iter = hasher.iterator(shape); int idx = 0; while (iter.hasNext()) { - assertEquals("Error at idx " + idx, Integer.valueOf(values[idx]), iter.next()); + assertEquals(Integer.valueOf(values[idx]), iter.next()); idx++; } assertEquals(5, idx); @@ -203,12 +202,10 @@ public void testConstructor_Iterator_ValueTooBig() { final int[] values = {shape.getNumberOfBits(), 3, 5, 7, 9, 3, 5, 1}; final Iterator iter = Arrays.stream(values).iterator(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new StaticHasher(iter, shape); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing - } + }); + assertNotNull(exception.getMessage()); } /** @@ -220,12 +217,10 @@ public void testConstructor_Iterator_ValueTooSmall() { final int[] values = {-1, 3, 5, 7, 9, 3, 5, 1}; final Iterator iter = Arrays.stream(values).iterator(); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new StaticHasher(iter, shape); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing - } + }); + assertNotNull(exception.getMessage()); } /** @@ -252,12 +247,10 @@ public void testConstructor_StaticHasher_WrongShape() { final Iterator iter = Arrays.stream(values).iterator(); final StaticHasher hasher = new StaticHasher(iter, new Shape(testFunctionX, 3, 72, 17)); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { new StaticHasher(hasher, shape); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing - } + }); + assertNotNull(exception.getMessage()); } /** @@ -305,11 +298,9 @@ public void testGetBits_WrongShape() { final List lst = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); final StaticHasher hasher = new StaticHasher(lst.iterator(), shape); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { hasher.iterator(new Shape(testFunctionX, 3, 72, 17)); - fail("Should have thrown IllegalArgumentException"); - } catch (final IllegalArgumentException expected) { - // do nothing - } + }); + assertNotNull(exception.getMessage()); } } diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/AbstractHashFunctionTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/AbstractHashFunctionTest.java index 740de16a15..5498d699cb 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/AbstractHashFunctionTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/AbstractHashFunctionTest.java @@ -16,11 +16,11 @@ */ package org.apache.commons.collections4.bloomfilter.hasher.function; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.collections4.bloomfilter.hasher.HashFunction; import org.apache.commons.collections4.bloomfilter.hasher.HashFunctionIdentity; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the signature of a hash function. diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/MD5CyclicTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/MD5CyclicTest.java index a0d837f252..9b0d9a83e1 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/MD5CyclicTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/MD5CyclicTest.java @@ -16,10 +16,10 @@ */ package org.apache.commons.collections4.bloomfilter.hasher.function; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.collections4.bloomfilter.hasher.HashFunction; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the MD5 cyclic hash function. diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/Murmur128x64CyclicTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/Murmur128x64CyclicTest.java index d576931175..9e17c2ec89 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/Murmur128x64CyclicTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/Murmur128x64CyclicTest.java @@ -16,11 +16,11 @@ */ package org.apache.commons.collections4.bloomfilter.hasher.function; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.charset.StandardCharsets; import org.apache.commons.collections4.bloomfilter.hasher.HashFunction; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test that the Murmur3 128 x64 hash function works correctly. diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/Murmur32x86IterativeTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/Murmur32x86IterativeTest.java index ac2e462aed..bca60c1e4b 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/Murmur32x86IterativeTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/Murmur32x86IterativeTest.java @@ -16,11 +16,11 @@ */ package org.apache.commons.collections4.bloomfilter.hasher.function; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.charset.StandardCharsets; import org.apache.commons.collections4.bloomfilter.hasher.HashFunction; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test that the Murmur3 32 x86 hash function works correctly. diff --git a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/ObjectsHashIterativeTest.java b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/ObjectsHashIterativeTest.java index cc013391af..5595efdc77 100644 --- a/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/ObjectsHashIterativeTest.java +++ b/src/test/java/org/apache/commons/collections4/bloomfilter/hasher/function/ObjectsHashIterativeTest.java @@ -16,12 +16,12 @@ */ package org.apache.commons.collections4.bloomfilter.hasher.function; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.charset.StandardCharsets; import java.util.Arrays; import org.apache.commons.collections4.bloomfilter.hasher.HashFunction; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests that the Objects hash works correctly. 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..655f92f2f2 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,42 @@ 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()) { + 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()) { + 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()) { + 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()) { + assertNotNull(exception.getMessage()); } // make sure things didn't change even if the expected exception was // thrown. @@ -663,8 +667,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 +685,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 +697,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 +705,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 +724,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 +739,37 @@ 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()) { + 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()) { + assertNotNull(exception.getMessage()); } // make sure nothing has changed after non-modification verify(); @@ -788,21 +785,21 @@ 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()) { + 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()) { + assertTrue(exception.getMessage().contains("Iterator")); } verify(); @@ -835,17 +832,17 @@ 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()) { + assertNotNull(exception.getMessage()); } } @@ -860,7 +857,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 +872,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 +900,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 +913,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 +923,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 +953,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 +968,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 +995,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 +1015,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 +1042,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 +1063,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 +1084,7 @@ public void testCollectionToArray() { } } for (final boolean element : matched) { - assertTrue("Collection should return all its elements in " + "toArray", element); + assertTrue(element); } } @@ -1107,25 +1096,22 @@ 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()) { + 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 +1164,54 @@ 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()) { + 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()) { + 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()) { + 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()) { + 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()) { + 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()) { + assertTrue(exception.getMessage().contains("remove() is not supported")); } verify(); @@ -1241,28 +1227,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 +1253,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/PredicatedCollectionBuilderTest.java b/src/test/java/org/apache/commons/collections4/collection/PredicatedCollectionBuilderTest.java index 37334a29ec..a7adf978e4 100644 --- a/src/test/java/org/apache/commons/collections4/collection/PredicatedCollectionBuilderTest.java +++ b/src/test/java/org/apache/commons/collections4/collection/PredicatedCollectionBuilderTest.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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -24,8 +29,7 @@ import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.Predicate; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests the PredicatedCollection.Builder class. @@ -41,7 +45,7 @@ public class PredicatedCollectionBuilderTest { public void addPass() { final PredicatedCollection.Builder builder = PredicatedCollection.notNullBuilder(); builder.add("test"); - Assert.assertEquals(builder.createPredicatedList().size(), 1); + assertEquals(builder.createPredicatedList().size(), 1); } /** @@ -51,9 +55,9 @@ public void addPass() { public void addFail() { final PredicatedCollection.Builder builder = PredicatedCollection.notNullBuilder(); builder.add((String) null); - Assert.assertTrue(builder.createPredicatedList().isEmpty()); + assertTrue(builder.createPredicatedList().isEmpty()); - Assert.assertEquals(1, builder.rejectedElements().size()); + assertEquals(1, builder.rejectedElements().size()); } /** @@ -63,7 +67,7 @@ public void addFail() { public void addAllPass() { final PredicatedCollection.Builder builder = PredicatedCollection.notNullBuilder(); builder.addAll(Arrays.asList("test1", null, "test2")); - Assert.assertEquals(builder.createPredicatedList().size(), 2); + assertEquals(builder.createPredicatedList().size(), 2); } @Test @@ -86,17 +90,15 @@ public void createPredicatedCollectionWithNotNullPredicate() { } private void checkPredicatedCollection1(final Collection collection) { - Assert.assertEquals(1, collection.size()); + assertEquals(1, collection.size()); collection.add("test2"); - Assert.assertEquals(2, collection.size()); + assertEquals(2, collection.size()); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { collection.add(null); - Assert.fail("Expecting IllegalArgumentException for failing predicate!"); - } catch (final IllegalArgumentException iae) { - // expected - } + }); + assertNotNull(exception.getMessage()); } @Test @@ -122,17 +124,16 @@ public void createPredicatedCollectionWithPredicate() { } private void checkPredicatedCollection2(final Collection collection) { - Assert.assertEquals(2, collection.size()); + assertEquals(2, collection.size()); - try { + Exception exception = assertThrows(IllegalArgumentException.class, () -> { collection.add(4); - Assert.fail("Expecting IllegalArgumentException for failing predicate!"); - } catch (final IllegalArgumentException iae) { - } - Assert.assertEquals(2, collection.size()); + }); + assertNotNull(exception.getMessage()); + assertEquals(2, collection.size()); collection.add(5); - Assert.assertEquals(3, collection.size()); + assertEquals(3, collection.size()); } private static class OddPredicate implements Predicate { 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/AbstractComparatorTest.java b/src/test/java/org/apache/commons/collections4/comparators/AbstractComparatorTest.java index 38e9f16dc9..9cbf5b7cd1 100644 --- a/src/test/java/org/apache/commons/collections4/comparators/AbstractComparatorTest.java +++ b/src/test/java/org/apache/commons/collections4/comparators/AbstractComparatorTest.java @@ -16,6 +16,10 @@ */ package org.apache.commons.collections4.comparators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.FileNotFoundException; import java.io.IOException; import java.io.Serializable; @@ -25,7 +29,6 @@ import java.util.List; import org.apache.commons.collections4.AbstractObjectTest; -import org.junit.Test; /** * Abstract test class for testing the Comparator interface. @@ -104,20 +107,18 @@ protected void sortObjects(final List list, final Comparator compa /** * Test sorting an empty list */ - @Test public void testEmptyListSort() { final List list = new LinkedList<>(); sortObjects(list, makeObject()); final List list2 = new LinkedList<>(); - assertEquals("Comparator cannot sort empty lists", list2, list); + assertEquals(list2, list); } /** * Test sorting a reversed list. */ - @Test public void testReverseListSort() { final Comparator comparator = makeObject(); @@ -127,13 +128,12 @@ public void testReverseListSort() { final List orderedList = getComparableObjectsOrdered(); - assertEquals("Comparator did not reorder the List correctly", orderedList, randomList); + assertEquals(orderedList, randomList); } /** * Test sorting a random list. */ - @Test public void testRandomListSort() { final Comparator comparator = makeObject(); @@ -150,17 +150,15 @@ public void testRandomListSort() { } */ - assertEquals("Comparator did not reorder the List correctly", orderedList, randomList); + assertEquals(orderedList, randomList); } /** * Nearly all Comparators should be Serializable. */ - @Test public void testComparatorIsSerializable() { final Comparator comparator = makeObject(); - assertTrue("This comparator should be Serializable.", - comparator instanceof Serializable); + assertTrue(comparator instanceof Serializable); } public String getCanonicalComparatorName(final Object object) { @@ -180,7 +178,6 @@ public String getCanonicalComparatorName(final Object object) { * against the canonical version in SCM. */ @SuppressWarnings("unchecked") - @Test public void testComparatorCompatibility() throws IOException, ClassNotFoundException { if (!skipSerializedCanonicalTests()) { Comparator comparator = null; @@ -213,7 +210,7 @@ public void testComparatorCompatibility() throws IOException, ClassNotFoundExcep final List orderedList = getComparableObjectsOrdered(); - assertEquals("Comparator did not reorder the List correctly", orderedList, randomList); + assertEquals(orderedList, randomList); } } } 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..80bbd92a30 100644 --- a/src/test/java/org/apache/commons/collections4/comparators/BooleanComparatorTest.java +++ b/src/test/java/org/apache/commons/collections4/comparators/BooleanComparatorTest.java @@ -16,14 +16,20 @@ */ package org.apache.commons.collections4.comparators; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +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; import java.util.List; -import org.junit.Test; -import static org.junit.Assert.assertNotEquals; + /** * Tests for {@link BooleanComparator}. @@ -65,15 +71,12 @@ public String getCompatibilityVersion() { // tests // ------------------------------------------------------------------------ - @Test public void testConstructors() { allTests(false, new BooleanComparator()); allTests(false, new BooleanComparator(false)); allTests(true, new BooleanComparator(true)); } - @Test - public void testStaticFactoryMethods() { allTests(false, BooleanComparator.getFalseFirstComparator()); allTests(false, BooleanComparator.booleanComparator(false)); @@ -81,7 +84,6 @@ public void testStaticFactoryMethods() { allTests(true, BooleanComparator.booleanComparator(true)); } - @Test public void testEqualsCompatibleInstance() { assertEquals(new BooleanComparator(), new BooleanComparator(false)); assertEquals(new BooleanComparator(false), new BooleanComparator(false)); @@ -130,35 +132,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..24f5bef6c1 100644 --- a/src/test/java/org/apache/commons/collections4/comparators/ComparatorChainTest.java +++ b/src/test/java/org/apache/commons/collections4/comparators/ComparatorChainTest.java @@ -16,13 +16,16 @@ */ package org.apache.commons.collections4.comparators; +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.io.Serializable; import java.util.Arrays; import java.util.Comparator; import java.util.LinkedList; import java.util.List; -import org.junit.Test; /** * Tests for ComparatorChain. @@ -51,7 +54,6 @@ public String getCompatibilityVersion() { // writeExternalFormToDisk((java.io.Serializable) makeObject(), "src/test/resources/data/test/ComparatorChain.version4.obj"); // } - @Test public void testNoopComparatorChain() { final ComparatorChain chain = new ComparatorChain<>(); final Integer i1 = 4; @@ -59,22 +61,19 @@ public void testNoopComparatorChain() { chain.addComparator(new ComparableComparator<>()); final int correctValue = i1.compareTo(i2); - assertEquals("Comparison returns the right order", chain.compare(i1, i2), correctValue); + assertEquals(chain.compare(i1, i2), correctValue); } - @Test 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 public void testListComparatorChain() { final List> list = new LinkedList<>(); list.add(new ComparableComparator<>()); @@ -83,23 +82,20 @@ public void testListComparatorChain() { final Integer i2 = 6; final int correctValue = i1.compareTo(i2); - assertEquals("Comparison returns the right order", chain.compare(i1, i2), correctValue); + assertEquals(chain.compare(i1, i2), correctValue); } - @Test public void testBadListComparatorChain() { final List> list = new LinkedList<>(); 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 public void testComparatorChainOnMinvaluedCompatator() { // -1 * Integer.MIN_VALUE is less than 0, // test that ComparatorChain handles this edge case correctly 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 193569c726..57acad35c3 100644 --- a/src/test/java/org/apache/commons/collections4/comparators/FixedOrderComparatorTest.java +++ b/src/test/java/org/apache/commons/collections4/comparators/FixedOrderComparatorTest.java @@ -16,13 +16,15 @@ */ 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; import java.util.List; import java.util.Random; -import org.junit.Test; /** * Test class for FixedOrderComparator. @@ -84,7 +86,6 @@ public String getCompatibilityVersion() { /** * Tests that the constructor plus add method compares items properly. */ - @Test public void testConstructorPlusAdd() { final FixedOrderComparator comparator = new FixedOrderComparator<>(); for (final String topCity : topCities) { @@ -97,7 +98,6 @@ public void testConstructorPlusAdd() { /** * Tests that the array constructor compares items properly. */ - @Test public void testArrayConstructor() { final String[] keys = topCities.clone(); final String[] topCitiesForTest = topCities.clone(); @@ -111,7 +111,6 @@ public void testArrayConstructor() { /** * Tests the list constructor. */ - @Test public void testListConstructor() { final String[] keys = topCities.clone(); final List topCitiesForTest = new LinkedList<>(Arrays.asList(topCities)); @@ -125,7 +124,6 @@ public void testListConstructor() { /** * Tests addAsEqual method. */ - @Test public void testAddAsEqual() { final FixedOrderComparator comparator = new FixedOrderComparator<>(topCities); comparator.addAsEqual("New York", "Minneapolis"); @@ -137,45 +135,37 @@ public void testAddAsEqual() { /** * Tests whether or not updates are disabled after a comparison is made. */ - @Test public void testLock() { final FixedOrderComparator comparator = new FixedOrderComparator<>(topCities); 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/comparators/ReverseComparatorTest.java b/src/test/java/org/apache/commons/collections4/comparators/ReverseComparatorTest.java index f8b2e4f471..388f5ae355 100644 --- a/src/test/java/org/apache/commons/collections4/comparators/ReverseComparatorTest.java +++ b/src/test/java/org/apache/commons/collections4/comparators/ReverseComparatorTest.java @@ -25,7 +25,6 @@ import java.util.LinkedList; import java.util.List; -import org.junit.Test; /** * Tests for ReverseComparator. @@ -78,7 +77,6 @@ public List getComparableObjectsOrdered() { * already "canonized" the comparator returned by makeComparator. */ @Override - @Test public void testSerializeDeserializeThenCompare() throws Exception { final Comparator comp = new ReverseComparator<>(new ComparableComparator()); @@ -90,7 +88,7 @@ public void testSerializeDeserializeThenCompare() throws Exception { final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buffer.toByteArray())); final Object dest = in.readObject(); in.close(); - assertEquals("obj != deserialize(serialize(obj))", comp, dest); + assertEquals(comp, dest); } } diff --git a/src/test/java/org/apache/commons/collections4/comparators/TransformingComparatorTest.java b/src/test/java/org/apache/commons/collections4/comparators/TransformingComparatorTest.java index e9df2887cc..8aaa87129a 100644 --- a/src/test/java/org/apache/commons/collections4/comparators/TransformingComparatorTest.java +++ b/src/test/java/org/apache/commons/collections4/comparators/TransformingComparatorTest.java @@ -66,12 +66,10 @@ public void testEquals() { final TransformingComparator comp2 = new TransformingComparator<>(t1, comp1); // Checks the contract: equals-hashcode on comp1 and comp2 - assertTrue("Contract failed: equals-hashcode", - comp1.equals(comp2) ? comp1.hashCode() == comp2.hashCode() : true); + assertTrue(comp1.equals(comp2) ? comp1.hashCode() == comp2.hashCode() : true); // Checks the contract: equals-hashcode on comp1 and comp2 - assertTrue("Contract failed: equals-hashcode", - comp2.equals(comp1) ? comp2.hashCode() == comp1.hashCode() : true); + assertTrue(comp2.equals(comp1) ? comp2.hashCode() == comp1.hashCode() : true); } @Override diff --git a/src/test/java/org/apache/commons/collections4/functors/AbstractAnyAllOnePredicateTest.java b/src/test/java/org/apache/commons/collections4/functors/AbstractAnyAllOnePredicateTest.java index 3f0d845989..816a1d2b00 100644 --- a/src/test/java/org/apache/commons/collections4/functors/AbstractAnyAllOnePredicateTest.java +++ b/src/test/java/org/apache/commons/collections4/functors/AbstractAnyAllOnePredicateTest.java @@ -18,10 +18,10 @@ import org.apache.commons.collections4.Predicate; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; import java.util.Collections; @@ -50,7 +50,7 @@ protected AbstractAnyAllOnePredicateTest(final T testValue) { public final void singleElementArrayToGetInstance() { final Predicate predicate = createMockPredicate(null); final Predicate allPredicate = getPredicateInstance(predicate); - assertSame("expected argument to be returned by getInstance()", predicate, allPredicate); + assertSame(predicate, allPredicate); } /** @@ -63,8 +63,7 @@ public final void singletonCollectionToGetInstance() { final Predicate predicate = createMockPredicate(null); final Predicate allPredicate = getPredicateInstance( Collections.>singleton(predicate)); - assertSame("expected singleton collection member to be returned by getInstance()", - predicate, allPredicate); + assertSame(predicate, allPredicate); } /** diff --git a/src/test/java/org/apache/commons/collections4/functors/AbstractClosureTest.java b/src/test/java/org/apache/commons/collections4/functors/AbstractClosureTest.java index d540127cf0..3806b81929 100644 --- a/src/test/java/org/apache/commons/collections4/functors/AbstractClosureTest.java +++ b/src/test/java/org/apache/commons/collections4/functors/AbstractClosureTest.java @@ -16,16 +16,17 @@ */ package org.apache.commons.collections4.functors; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.apache.commons.collections4.Closure; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public abstract class AbstractClosureTest { @Test public void closureSanityTests() throws Exception { final Closure closure = generateClosure(); - Assert.assertNotNull(closure); + assertNotNull(closure); } /** diff --git a/src/test/java/org/apache/commons/collections4/functors/AbstractCompositePredicateTest.java b/src/test/java/org/apache/commons/collections4/functors/AbstractCompositePredicateTest.java index a9e7425386..89e9259ed8 100644 --- a/src/test/java/org/apache/commons/collections4/functors/AbstractCompositePredicateTest.java +++ b/src/test/java/org/apache/commons/collections4/functors/AbstractCompositePredicateTest.java @@ -16,15 +16,18 @@ */ package org.apache.commons.collections4.functors; +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.Collections; import java.util.List; import org.apache.commons.collections4.Predicate; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Base class for tests of composite predicates. * @@ -82,7 +85,7 @@ protected final Predicate getPredicateInstance(final Boolean... mockReturnVal public void singleElementArrayToGetInstance() { final Predicate predicate = createMockPredicate(null); final Predicate allPredicate = getPredicateInstance(predicate); - Assert.assertSame("expected argument to be returned by getInstance()", predicate, allPredicate); + assertSame(predicate, allPredicate); } /** @@ -93,52 +96,67 @@ public void singletonCollectionToGetInstance() { final Predicate predicate = createMockPredicate(null); final Predicate allPredicate = getPredicateInstance( Collections.>singleton(predicate)); - Assert.assertSame("expected argument to be returned by getInstance()", predicate, allPredicate); + assertSame(predicate, allPredicate); } /** * Tests {@code getInstance} with a null predicate array. */ - @Test(expected = NullPointerException.class) + @Test public final void nullArrayToGetInstance() { - getPredicateInstance((Predicate[]) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + getPredicateInstance((Predicate[]) null); + }); + assertTrue(exception.getMessage().contains("predicates")); } /** * Tests {@code getInstance} with a single null element in the predicate array. */ @SuppressWarnings({"unchecked"}) - @Test(expected = NullPointerException.class) + @Test public final void nullElementInArrayToGetInstance() { - getPredicateInstance(new Predicate[] { null }); + Exception exception = assertThrows(NullPointerException.class, () -> { + getPredicateInstance(new Predicate[] { null }); + }); + assertTrue(exception.getMessage().contains("predicates")); } /** * Tests {@code getInstance} with two null elements in the predicate array. */ @SuppressWarnings({"unchecked"}) - @Test(expected = NullPointerException.class) + @Test public final void nullElementsInArrayToGetInstance() { - getPredicateInstance(new Predicate[] { null, null }); + Exception exception = assertThrows(NullPointerException.class, () -> { + getPredicateInstance(new Predicate[] { null, null }); + }); + assertTrue(exception.getMessage().contains("predicates")); } /** * Tests {@code getInstance} with a null predicate collection */ - @Test(expected = NullPointerException.class) + @Test public final void nullCollectionToGetInstance() { - getPredicateInstance((Collection>) null); + Exception exception = assertThrows(NullPointerException.class, () -> { + getPredicateInstance((Collection>) null); + }); + assertTrue(exception.getMessage().contains("predicates")); } /** * Tests {@code getInstance} with a predicate collection that contains null elements */ - @Test(expected = NullPointerException.class) + @Test public final void nullElementsInCollectionToGetInstance() { final Collection> coll = new ArrayList<>(); coll.add(null); coll.add(null); - getPredicateInstance(coll); + Exception exception = assertThrows(NullPointerException.class, () -> { + getPredicateInstance(coll); + }); + assertTrue(exception.getMessage().contains("predicates")); } } diff --git a/src/test/java/org/apache/commons/collections4/functors/AbstractMockPredicateTest.java b/src/test/java/org/apache/commons/collections4/functors/AbstractMockPredicateTest.java index daf4c95b4d..077461932f 100644 --- a/src/test/java/org/apache/commons/collections4/functors/AbstractMockPredicateTest.java +++ b/src/test/java/org/apache/commons/collections4/functors/AbstractMockPredicateTest.java @@ -21,8 +21,8 @@ import static org.easymock.EasyMock.verify; import static org.easymock.EasyMock.replay; -import org.junit.Before; -import org.junit.After; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.AfterEach; import org.apache.commons.collections4.Predicate; import org.easymock.EasyMock; @@ -55,7 +55,7 @@ protected AbstractMockPredicateTest(final T testValue) { /** * Creates the list of predicates to verify. */ - @Before + @BeforeEach public final void createVerifyList() { mockPredicatesToVerify = new ArrayList<>(); } @@ -63,7 +63,7 @@ public final void createVerifyList() { /** * Verifies all the mock predicates created for the test. */ - @After + @AfterEach public final void verifyPredicates() { for (final Predicate predicate : mockPredicatesToVerify) { verify(predicate); diff --git a/src/test/java/org/apache/commons/collections4/functors/AbstractPredicateTest.java b/src/test/java/org/apache/commons/collections4/functors/AbstractPredicateTest.java index 9ef75cf6a9..f142e7e5b7 100644 --- a/src/test/java/org/apache/commons/collections4/functors/AbstractPredicateTest.java +++ b/src/test/java/org/apache/commons/collections4/functors/AbstractPredicateTest.java @@ -16,17 +16,20 @@ */ package org.apache.commons.collections4.functors; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.commons.collections4.Predicate; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public abstract class AbstractPredicateTest { protected Object cObject; protected String cString; protected Integer cInteger; - @Before + @BeforeEach public void initialiseTestObjects() throws Exception { cObject = new Object(); cString = "Hello"; @@ -36,7 +39,7 @@ public void initialiseTestObjects() throws Exception { @Test public void predicateSanityTests() throws Exception { final Predicate predicate = generatePredicate(); - Assert.assertNotNull(predicate); + assertNotNull(predicate); } /** @@ -45,10 +48,10 @@ public void predicateSanityTests() throws Exception { protected abstract Predicate generatePredicate(); protected void assertPredicateFalse(final Predicate predicate, final T testObject) { - Assert.assertFalse(predicate.evaluate(testObject)); + assertFalse(predicate.evaluate(testObject)); } protected void assertPredicateTrue(final Predicate predicate, final T testObject) { - Assert.assertTrue(predicate.evaluate(testObject)); + assertTrue(predicate.evaluate(testObject)); } } diff --git a/src/test/java/org/apache/commons/collections4/functors/AllPredicateTest.java b/src/test/java/org/apache/commons/collections4/functors/AllPredicateTest.java index 56584d86bc..3a0aaca1f9 100644 --- a/src/test/java/org/apache/commons/collections4/functors/AllPredicateTest.java +++ b/src/test/java/org/apache/commons/collections4/functors/AllPredicateTest.java @@ -19,9 +19,9 @@ import org.apache.commons.collections4.Predicate; import static org.apache.commons.collections4.functors.AllPredicate.allPredicate; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.Test; import java.util.Collection; import java.util.Collections; @@ -63,7 +63,7 @@ protected final Predicate getPredicateInstance(final Collection allPredicate = getPredicateInstance( Collections.>emptyList()); - assertTrue("empty collection not true", allPredicate.evaluate(getTestValue())); + assertTrue(allPredicate.evaluate(getTestValue())); } /** @@ -86,8 +86,7 @@ public void oneTruePredicate() { // an array of size one. final Predicate predicate = createMockPredicate(true); - assertTrue("single true predicate evaluated to false", - allPredicate(predicate).evaluate(getTestValue())); + assertTrue(allPredicate(predicate).evaluate(getTestValue())); } /** @@ -99,8 +98,7 @@ public void oneFalsePredicate() { // use the constructor directly, as getInstance() returns the original predicate when passed // an array of size one. final Predicate predicate = createMockPredicate(false); - assertFalse("single false predicate evaluated to true", - allPredicate(predicate).evaluate(getTestValue())); + assertFalse(allPredicate(predicate).evaluate(getTestValue())); } /** @@ -108,10 +106,8 @@ public void oneFalsePredicate() { */ @Test public void allTrue() { - assertTrue("multiple true predicates evaluated to false", - getPredicateInstance(true, true).evaluate(getTestValue())); - assertTrue("multiple true predicates evaluated to false", - getPredicateInstance(true, true, true).evaluate(getTestValue())); + assertTrue(getPredicateInstance(true, true).evaluate(getTestValue())); + assertTrue(getPredicateInstance(true, true, true).evaluate(getTestValue())); } /** @@ -120,15 +116,10 @@ public void allTrue() { */ @Test public void trueAndFalseCombined() { - assertFalse("false predicate evaluated to true", - getPredicateInstance(false, null).evaluate(getTestValue())); - assertFalse("false predicate evaluated to true", - getPredicateInstance(false, null, null).evaluate(getTestValue())); - assertFalse("false predicate evaluated to true", - getPredicateInstance(true, false, null).evaluate(getTestValue())); - assertFalse("false predicate evaluated to true", - getPredicateInstance(true, true, false).evaluate(getTestValue())); - assertFalse("false predicate evaluated to true", - getPredicateInstance(true, true, false, null).evaluate(getTestValue())); + assertFalse(getPredicateInstance(false, null).evaluate(getTestValue())); + assertFalse(getPredicateInstance(false, null, null).evaluate(getTestValue())); + assertFalse(getPredicateInstance(true, false, null).evaluate(getTestValue())); + assertFalse(getPredicateInstance(true, true, false).evaluate(getTestValue())); + assertFalse(getPredicateInstance(true, true, false, null).evaluate(getTestValue())); } } diff --git a/src/test/java/org/apache/commons/collections4/functors/CatchAndRethrowClosureTest.java b/src/test/java/org/apache/commons/collections4/functors/CatchAndRethrowClosureTest.java index 3f7240089f..33ef1e2d59 100644 --- a/src/test/java/org/apache/commons/collections4/functors/CatchAndRethrowClosureTest.java +++ b/src/test/java/org/apache/commons/collections4/functors/CatchAndRethrowClosureTest.java @@ -16,12 +16,14 @@ */ package org.apache.commons.collections4.functors; +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 org.apache.commons.collections4.Closure; -import org.apache.commons.collections4.FunctorException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class CatchAndRethrowClosureTest extends AbstractClosureTest { @@ -61,33 +63,19 @@ protected Closure generateClosure() { @Test public void testThrowingClosure() { - Closure closure = generateNoExceptionClosure(); - try { - closure.execute(Integer.valueOf(0)); - } catch (final FunctorException ex) { - Assert.fail(); - } catch (final RuntimeException ex) { - Assert.fail(); - } + final Closure closure = generateNoExceptionClosure(); + closure.execute(Integer.valueOf(0)); - closure = generateIOExceptionClosure(); - try { - closure.execute(Integer.valueOf(0)); - Assert.fail(); - } catch (final FunctorException ex) { - Assert.assertTrue(ex.getCause() instanceof IOException); - } catch (final RuntimeException ex) { - Assert.fail(); - } + final Closure closure1 = generateIOExceptionClosure(); + Exception exception = assertThrows(Exception.class, () -> { + closure1.execute(Integer.valueOf(0)); + }); + assertTrue(exception.getMessage().contains("IOException")); - closure = generateNullPointerExceptionClosure(); - try { - closure.execute(Integer.valueOf(0)); - Assert.fail(); - } catch (final FunctorException ex) { - Assert.fail(); - } catch (final RuntimeException ex) { - Assert.assertTrue(ex instanceof NullPointerException); - } + final Closure closure2 = generateNullPointerExceptionClosure(); + exception = assertThrows(Exception.class, () -> { + closure2.execute(Integer.valueOf(0)); + }); + assertNull(exception.getMessage()); } } diff --git a/src/test/java/org/apache/commons/collections4/functors/ComparatorPredicateTest.java b/src/test/java/org/apache/commons/collections4/functors/ComparatorPredicateTest.java index afda1fc07e..d33e8026c3 100644 --- a/src/test/java/org/apache/commons/collections4/functors/ComparatorPredicateTest.java +++ b/src/test/java/org/apache/commons/collections4/functors/ComparatorPredicateTest.java @@ -21,7 +21,7 @@ import java.util.Comparator; import org.apache.commons.collections4.Predicate; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class ComparatorPredicateTest extends AbstractPredicateTest { diff --git a/src/test/java/org/apache/commons/collections4/functors/EqualPredicateTest.java b/src/test/java/org/apache/commons/collections4/functors/EqualPredicateTest.java index 3ff4861fa6..1695ab5c2d 100644 --- a/src/test/java/org/apache/commons/collections4/functors/EqualPredicateTest.java +++ b/src/test/java/org/apache/commons/collections4/functors/EqualPredicateTest.java @@ -18,10 +18,10 @@ import static org.apache.commons.collections4.functors.EqualPredicate.equalPredicate; import static org.apache.commons.collections4.functors.NullPredicate.nullPredicate; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; import org.apache.commons.collections4.Predicate; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class EqualPredicateTest extends AbstractPredicateTest { diff --git a/src/test/java/org/apache/commons/collections4/functors/NullPredicateTest.java b/src/test/java/org/apache/commons/collections4/functors/NullPredicateTest.java index 652f7c8bb7..d41d8dcdb6 100644 --- a/src/test/java/org/apache/commons/collections4/functors/NullPredicateTest.java +++ b/src/test/java/org/apache/commons/collections4/functors/NullPredicateTest.java @@ -17,10 +17,10 @@ package org.apache.commons.collections4.functors; import static org.apache.commons.collections4.functors.NullPredicate.nullPredicate; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertSame; import org.apache.commons.collections4.Predicate; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class NullPredicateTest extends AbstractPredicateTest { @Test 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..0b49a9dd70 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; @@ -23,7 +29,6 @@ import java.util.List; import java.util.NoSuchElementException; -import org.junit.Test; /** * A unit test to test the basic functions of {@link BoundedIterator}. @@ -67,7 +72,6 @@ public Iterator makeObject() { * at an index greater its first element, and the last element returned is * at an index less than its last element. */ - @Test public void testBounded() { final Iterator iter = new BoundedIterator<>(testList.iterator(), 2, 4); @@ -81,11 +85,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()); } /** @@ -93,7 +96,6 @@ public void testBounded() { * zero and the {@code max} is its size, in that the BoundedIterator * should return all the same elements as its decorated iterator. */ - @Test public void testSameAsDecorated() { final Iterator iter = new BoundedIterator<>(testList.iterator(), 0, testList.size()); @@ -114,11 +116,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()); } /** @@ -126,41 +127,35 @@ public void testSameAsDecorated() { * BoundedIterator should behave as if there are no more elements to return, * since it is technically an empty iterator. */ - @Test 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()); } /** * Test the case if a negative {@code offset} is passed to the * constructor. {@link IllegalArgumentException} is expected. */ - @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")); } /** * Test the case if a negative {@code max} is passed to the * constructor. {@link IllegalArgumentException} is expected. */ - @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.")); } /** @@ -168,15 +163,13 @@ public void testNegativeMax() { * greater than the decorated iterator's size. The BoundedIterator should * behave as if there are no more elements to return. */ - @Test 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()); } /** @@ -185,7 +178,6 @@ public void testOffsetGreaterThanSize() { * returned should be the same as the last element of the decorated * iterator. */ - @Test public void testMaxGreaterThanSize() { final Iterator iter = new BoundedIterator<>(testList.iterator(), 1, 10); @@ -203,34 +195,30 @@ 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()); } /** * Test the {@code remove()} method being called without * {@code next()} being called first. */ - @Test 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()")); } /** * Test the {@code remove()} method being called twice without calling * {@code next()} in between. */ - @Test public void testRemoveCalledTwice() { final List testListCopy = new ArrayList<>(testList); final Iterator iter = new BoundedIterator<>(testListCopy.iterator(), 1, 5); @@ -239,18 +227,16 @@ 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()); } /** * Test removing the first element. Verify that the element is removed from * the underlying collection. */ - @Test public void testRemoveFirst() { final List testListCopy = new ArrayList<>(testList); final Iterator iter = new BoundedIterator<>(testListCopy.iterator(), 1, 5); @@ -271,18 +257,16 @@ 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()); } /** * Test removing an element in the middle of the iterator. Verify that the * element is removed from the underlying collection. */ - @Test public void testRemoveMiddle() { final List testListCopy = new ArrayList<>(testList); final Iterator iter = new BoundedIterator<>(testListCopy.iterator(), 1, 5); @@ -303,18 +287,16 @@ 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()); } /** * Test removing the last element. Verify that the element is removed from * the underlying collection. */ - @Test public void testRemoveLast() { final List testListCopy = new ArrayList<>(testList); final Iterator iter = new BoundedIterator<>(testListCopy.iterator(), 1, 5); @@ -331,28 +313,25 @@ 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()); } /** * Test the case if the decorated iterator does not support the * {@code remove()} method and throws an {@link UnsupportedOperationException}. */ - @Test public void testRemoveUnsupported() { final Iterator mockIterator = new AbstractIteratorDecorator(testList.iterator()) { @Override @@ -364,10 +343,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/FilterListIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/FilterListIteratorTest.java index 0507330bf2..a1d4fcc450 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/FilterListIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/FilterListIteratorTest.java @@ -16,6 +16,10 @@ */ 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.assertTrue; + import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -25,12 +29,9 @@ import org.apache.commons.collections4.Predicate; import org.apache.commons.collections4.PredicateUtils; import org.apache.commons.collections4.list.GrowthList; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Tests the FilterListIterator class. @@ -53,7 +54,7 @@ public class FilterListIteratorTest { private Predicate fourPred = null; private final Random random = new Random(); - @Before + @BeforeEach public void setUp() { list = new ArrayList<>(); odds = new ArrayList<>(); @@ -94,7 +95,7 @@ public void setUp() { } - @After + @AfterEach public void tearDown() throws Exception { list = null; odds = null; @@ -289,9 +290,9 @@ public void testCollections360() throws Throwable { final Collection> var7 = new GrowthList<>(); final Predicate var9 = PredicateUtils.anyPredicate(var7); final FilterListIterator var13 = new FilterListIterator<>(var9); - Assert.assertFalse(var13.hasNext()); + assertFalse(var13.hasNext()); final FilterListIterator var14 = new FilterListIterator<>(var9); - Assert.assertFalse(var14.hasPrevious()); + assertFalse(var14.hasPrevious()); } // Utilities @@ -403,25 +404,20 @@ private void walkLists(final List list, final ListIterator testing) { } // random walk - final StringBuilder walkdescr = new StringBuilder(500); for (int i = 0; i < 500; i++) { if (random.nextBoolean()) { // step forward - walkdescr.append("+"); if (expected.hasNext()) { - assertEquals(walkdescr.toString(), expected.next(), testing.next()); + assertEquals(expected.next(), testing.next()); } } else { // step backward - walkdescr.append("-"); if (expected.hasPrevious()) { - assertEquals(walkdescr.toString(), expected.previous(), testing.previous()); + assertEquals(expected.previous(), testing.previous()); } } - assertEquals(walkdescr.toString(), expected.nextIndex(), testing.nextIndex()); - assertEquals(walkdescr.toString(), expected.previousIndex(), testing.previousIndex()); + assertEquals(expected.nextIndex(), testing.nextIndex()); + assertEquals(expected.previousIndex(), testing.previousIndex()); } - } - } 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..64f6851cb9 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.*; +import org.junit.jupiter.api.Test; /** * 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 255dbbcbee..fc99f5a683 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 fd7e14cbab..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 element 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..6212764341 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/LoopingIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/LoopingIteratorTest.java @@ -16,14 +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.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.*; +import org.junit.jupiter.api.Test; /** * 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..4e89f4eb7a 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.*; +import org.junit.jupiter.api.Test; /** * 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 45b9caa551..5f12398533 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..4f94998148 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; @@ -23,7 +29,6 @@ import java.util.List; import java.util.NoSuchElementException; -import org.junit.Test; /** * Tests the PeekingIterator. @@ -65,13 +70,11 @@ public boolean supportsRemove() { //----------------------------------------------------------------------- - @Test public void testEmpty() { final Iterator it = makeEmptyIterator(); assertFalse(it.hasNext()); } - @Test @SuppressWarnings("unchecked") public void testSinglePeek() { final PeekingIterator it = makeObject(); @@ -80,7 +83,6 @@ public void testSinglePeek() { validate(it, (E[]) testArray); } - @Test public void testMultiplePeek() { final PeekingIterator it = makeObject(); assertEquals("a", it.peek()); @@ -97,7 +99,6 @@ public void testMultiplePeek() { assertFalse(it.hasNext()); } - @Test public void testIteratorExhausted() { final PeekingIterator it = makeObject(); it.next(); @@ -106,15 +107,12 @@ 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 public void testIllegalRemove() { final PeekingIterator it = makeObject(); it.next(); @@ -123,12 +121,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/PushbackIteratorTest.java b/src/test/java/org/apache/commons/collections4/iterators/PushbackIteratorTest.java index 77d0a1cfd2..144f1b2a1f 100644 --- a/src/test/java/org/apache/commons/collections4/iterators/PushbackIteratorTest.java +++ b/src/test/java/org/apache/commons/collections4/iterators/PushbackIteratorTest.java @@ -22,7 +22,6 @@ import java.util.Iterator; import java.util.List; -import org.junit.Test; /** * Tests the PushbackIterator. @@ -65,7 +64,6 @@ public boolean supportsRemove() { // ----------------------------------------------------------------------- - @Test public void testNormalIteration() { final PushbackIterator iter = makeObject(); assertEquals("a", iter.next()); @@ -74,7 +72,6 @@ public void testNormalIteration() { assertFalse(iter.hasNext()); } - @Test @SuppressWarnings("unchecked") public void testImmediatePushback() { final PushbackIterator iter = makeObject(); @@ -84,7 +81,6 @@ public void testImmediatePushback() { validate(iter, "b", "c"); } - @Test @SuppressWarnings("unchecked") public void testDelayedPushback() { final PushbackIterator iter = makeObject(); @@ -95,7 +91,6 @@ public void testDelayedPushback() { validate(iter, "c"); } - @Test @SuppressWarnings("unchecked") public void testMultiplePushback() { final PushbackIterator iter = makeObject(); 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..f570175e9c 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; @@ -23,7 +29,6 @@ import java.util.List; import java.util.NoSuchElementException; -import org.junit.Test; /** * A unit test to test the basic functions of {@link SkippingIterator}. @@ -67,7 +72,6 @@ public Iterator makeObject() { * at an index greater its first element, and the last element returned is * at an index less than its last element. */ - @Test public void testSkipping() { final Iterator iter = new SkippingIterator<>(testList.iterator(), 2); @@ -83,11 +87,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()); } /** @@ -95,7 +98,6 @@ public void testSkipping() { * zero, in that the SkippingIterator should return all the same elements * as its decorated iterator. */ - @Test public void testSameAsDecorated() { final Iterator iter = new SkippingIterator<>(testList.iterator(), 0); @@ -115,11 +117,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()); } /** @@ -127,51 +128,44 @@ public void testSameAsDecorated() { * greater than the decorated iterator's size. The SkippingIterator should * behave as if there are no more elements to return. */ - @Test 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()); } /** * Test the case if a negative {@code offset} is passed to the * constructor. {@link IllegalArgumentException} is expected. */ - @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")); } /** * Test the {@code remove()} method being called without * {@code next()} being called first. */ - @Test 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()")); } /** * Test the {@code remove()} method being called twice without calling * {@code next()} in between. */ - @Test public void testRemoveCalledTwice() { final List testListCopy = new ArrayList<>(testList); final Iterator iter = new SkippingIterator<>(testListCopy.iterator(), 1); @@ -180,18 +174,16 @@ 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()); } /** * Test removing the first element. Verify that the element is removed from * the underlying collection. */ - @Test public void testRemoveFirst() { final List testListCopy = new ArrayList<>(testList); final Iterator iter = new SkippingIterator<>(testListCopy.iterator(), 4); @@ -208,18 +200,16 @@ 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()); } /** * Test removing an element in the middle of the iterator. Verify that the * element is removed from the underlying collection. */ - @Test public void testRemoveMiddle() { final List testListCopy = new ArrayList<>(testList); final Iterator iter = new SkippingIterator<>(testListCopy.iterator(), 3); @@ -238,18 +228,16 @@ 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()); } /** * Test removing the last element. Verify that the element is removed from * the underlying collection. */ - @Test public void testRemoveLast() { final List testListCopy = new ArrayList<>(testList); final Iterator iter = new SkippingIterator<>(testListCopy.iterator(), 5); @@ -260,28 +248,25 @@ 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()); } /** * Test the case if the decorated iterator does not support the * {@code remove()} method and throws an {@link UnsupportedOperationException}. */ - @Test public void testRemoveUnsupported() { final Iterator mockIterator = new AbstractIteratorDecorator(testList.iterator()) { @Override @@ -293,10 +278,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/junit/AbstractAvailableLocalesTest.java b/src/test/java/org/apache/commons/collections4/junit/AbstractAvailableLocalesTest.java deleted file mode 100644 index 794051b87e..0000000000 --- a/src/test/java/org/apache/commons/collections4/junit/AbstractAvailableLocalesTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.collections4.junit; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -import org.apache.commons.lang3.reflect.FieldUtils; -import org.junit.Rule; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -@RunWith(Parameterized.class) -public abstract class AbstractAvailableLocalesTest { - -// public static List combine(final Object[] objects, final List locales) { -// final List result = new ArrayList<>(objects.length * locales.size()); -// Arrays.stream(objects).forEachOrdered(object -> locales.stream().forEachOrdered(locale -> result.add(new Object[] { object, locale }))); -// return result; -// } -// -// public static List combine(final Object[] objects, final Locale[] locales) { -// final List result = new ArrayList<>(objects.length * locales.length); -// Arrays.stream(objects).forEachOrdered(object -> Arrays.stream(locales).forEachOrdered(locale -> result.add(new Object[] { object, locale }))); -// return result; -// } - -// public static List combineAvailableLocales(final Object[] objects) { -// return combine(objects, getSortedAvailableLocales()); -// } -// -// public static List combineDeclaredLocales(final Object[] objects) { -// return combine(objects, getSortedDeclaredLocales()); -// } - - @Parameters(name = "{0}") - public static Locale[] getSortedAvailableLocales() { - final Locale[] availableLocales = Locale.getAvailableLocales(); - Arrays.sort(availableLocales, new ObjectToStringComparator()); - return availableLocales; - } - - public static List getSortedDeclaredLocales() { - final Field[] allFields = FieldUtils.getAllFields(Locale.class); - final List availableLocales = new ArrayList<>(allFields.length); - for (final Field field : allFields) { - final int modifiers = field.getModifiers(); - if (field.getType() == Locale.class && Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) { - try { - availableLocales.add((Locale) field.get(Locale.class)); - } catch (IllegalArgumentException | IllegalAccessException e) { - throw new IllegalStateException("Field " + field, e); - } - } - } - Collections.sort(availableLocales, new ObjectToStringComparator()); - return availableLocales; - } - - private final Locale locale; - - @Rule - public final SetDefaultLocaleTestRule rule; - - public AbstractAvailableLocalesTest(final Locale locale) { - super(); - this.locale = locale; - this.rule = new SetDefaultLocaleTestRule(locale); - } - - public Locale getLocale() { - return locale; - } -} - diff --git a/src/test/java/org/apache/commons/collections4/junit/ObjectToStringComparator.java b/src/test/java/org/apache/commons/collections4/junit/ObjectToStringComparator.java deleted file mode 100644 index c20746873f..0000000000 --- a/src/test/java/org/apache/commons/collections4/junit/ObjectToStringComparator.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.collections4.junit; - -import java.io.Serializable; -import java.util.Comparator; - -public final class ObjectToStringComparator implements Comparator, Serializable { - - private static final long serialVersionUID = 1L; - - @Override - public int compare(final Object o1, final Object o2) { - if (o1 == null && o2 == null) { - return 0; - } - if (o1 == null) { - return 1; - } - if (o2 == null) { - return -1; - } - return o1.toString().compareTo(o2.toString()); - } -} - diff --git a/src/test/java/org/apache/commons/collections4/junit/SetDefaultLocaleTestRule.java b/src/test/java/org/apache/commons/collections4/junit/SetDefaultLocaleTestRule.java deleted file mode 100644 index 54bb6ef170..0000000000 --- a/src/test/java/org/apache/commons/collections4/junit/SetDefaultLocaleTestRule.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.commons.collections4.junit; - -import java.util.Locale; - -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -/** - * Sets the default {@code Locale} to the given locale for the duration of the test. - */ -public class SetDefaultLocaleTestRule implements TestRule { - - private final Locale locale; - - public SetDefaultLocaleTestRule(final Locale locale) { - super(); - this.locale = locale; - } - - @Override - public Statement apply(final Statement base, final Description description) { - return new Statement() { - @Override - public void evaluate() throws Throwable { - final Locale savedLocale = Locale.getDefault(); - Locale.setDefault(getLocale()); - try { - base.evaluate(); - } finally { - Locale.setDefault(savedLocale); - } - } - }; - } - - public Locale getLocale() { - return locale; - } - -} - 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..bd1c0003d1 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.*; +import org.junit.jupiter.api.Test; /** * 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..5736474d86 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 org.junit.Test; +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.jupiter.api.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..c178ed1462 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.jupiter.api.Assertions.assertSame; + import java.util.Map; import org.apache.commons.collections4.KeyValue; -import org.junit.Test; +import org.junit.jupiter.api.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..0a61159df1 100644 --- a/src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.java +++ b/src/test/java/org/apache/commons/collections4/keyvalue/MultiKeyTest.java @@ -16,7 +16,14 @@ */ package org.apache.commons.collections4.keyvalue; -import org.junit.Test; +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.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -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/TiedMapEntryTest.java b/src/test/java/org/apache/commons/collections4/keyvalue/TiedMapEntryTest.java index b496e6a1db..c8ed8392b5 100644 --- a/src/test/java/org/apache/commons/collections4/keyvalue/TiedMapEntryTest.java +++ b/src/test/java/org/apache/commons/collections4/keyvalue/TiedMapEntryTest.java @@ -16,11 +16,12 @@ */ package org.apache.commons.collections4.keyvalue; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertSame; + +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.*; /** * Test the TiedMapEntry class. 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..0d8ec6c6a0 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.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Map; import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.Unmodifiable; -import org.junit.Test; +import org.junit.jupiter.api.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 bc54cd4beb..8dd2325ef6 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("Empty 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/Collections701Test.java b/src/test/java/org/apache/commons/collections4/list/Collections701Test.java index db261b6fc6..264a96251d 100644 --- a/src/test/java/org/apache/commons/collections4/list/Collections701Test.java +++ b/src/test/java/org/apache/commons/collections4/list/Collections701Test.java @@ -16,13 +16,14 @@ */ package org.apache.commons.collections4.list; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for COLLECTIONS-701. @@ -33,16 +34,16 @@ public class Collections701Test { public void testArrayList() { final List list = new ArrayList<>(); list.add(list); - Assert.assertEquals(1, list.size()); - Assert.assertEquals(list, list.get(0)); + assertEquals(1, list.size()); + assertEquals(list, list.get(0)); } @Test public void testHashSet() { final Set set = new HashSet<>(); set.add(set); - Assert.assertEquals(1, set.size()); - Assert.assertEquals(set, set.iterator().next()); + assertEquals(1, set.size()); + assertEquals(set, set.iterator().next()); } @Test @@ -50,7 +51,7 @@ public void testSetUniqueList() { final List source = new ArrayList<>(); final List list = SetUniqueList.setUniqueList(source); list.add(list); - Assert.assertEquals(1, list.size()); - Assert.assertEquals(list, list.get(0)); + assertEquals(1, list.size()); + assertEquals(list, list.get(0)); } } 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 029a8d2980..c4ef1938c4 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..6df0fbb879 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 greater 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 greater 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/LazyMapTest.java b/src/test/java/org/apache/commons/collections4/map/LazyMapTest.java index 7507076c96..76cc9fcc40 100644 --- a/src/test/java/org/apache/commons/collections4/map/LazyMapTest.java +++ b/src/test/java/org/apache/commons/collections4/map/LazyMapTest.java @@ -24,7 +24,6 @@ import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.FactoryUtils; import org.apache.commons.collections4.Transformer; -import org.junit.Test; /** * Extension of {@link AbstractMapTest} for exercising the @@ -52,7 +51,6 @@ public void testMapGet() { //TODO eliminate need for this via superclass - see svn history. } - @Test public void mapGetWithFactory() { Map map = lazyMap(new HashMap(), oneFactory); assertEquals(0, map.size()); @@ -70,7 +68,6 @@ public void mapGetWithFactory() { assertEquals(1, map.size()); } - @Test public void mapGetWithTransformer() { final Transformer intConverter = Number::intValue; final Map map = lazyMap(new HashMap(), intConverter); 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..d1d873aa15 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; @@ -28,7 +32,6 @@ import org.apache.commons.collections4.FactoryUtils; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.TransformerUtils; -import org.junit.Test; /** * Extension of {@link LazyMapTest} for exercising the @@ -71,7 +74,6 @@ public void testMapGet() { //TODO eliminate need for this via superclass - see svn history. } - @Test public void mapGet() { Map map = lazySortedMap(new TreeMap(), oneFactory); assertEquals(0, map.size()); @@ -81,7 +83,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()); } @@ -92,18 +94,14 @@ public void testSortOrder() { map.put("A", 5); map.get("B"); // Entry with value "One" created map.put("C", 8); - 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", - "B", map.tailMap("B").firstKey()); - assertEquals("Last key in head map should be B", - "B", map.headMap("C").lastKey()); - assertEquals("Last key in submap should be B", - "B", map.subMap("A", "C").lastKey()); + assertEquals("A", map.firstKey()); + assertEquals("C", map.lastKey()); + assertEquals("B", map.tailMap("B").firstKey()); + assertEquals("B", map.headMap("C").lastKey()); + assertEquals("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() { @@ -111,36 +109,28 @@ public void testReverseSortOrder() { map.put("A", 5); map.get("B"); // Entry with value "One" created map.put("C", 8); - 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", - "B", map.tailMap("B").firstKey()); - assertEquals("Last key in head map should be B", - "B", map.headMap("A").lastKey()); - assertEquals("Last key in submap should be B", - "B", map.subMap("C", "A").lastKey()); + assertEquals("A", map.lastKey()); + assertEquals("C", map.firstKey()); + assertEquals("B", map.tailMap("B").firstKey()); + assertEquals("B", map.headMap("A").lastKey()); + assertEquals("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 865c0adacd..ffa1e2038c 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 3e4a490126..cc499a6d0d 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/properties/AbstractPropertiesFactoryTest.java b/src/test/java/org/apache/commons/collections4/properties/AbstractPropertiesFactoryTest.java index 3e76c77344..0cb0aad2c4 100644 --- a/src/test/java/org/apache/commons/collections4/properties/AbstractPropertiesFactoryTest.java +++ b/src/test/java/org/apache/commons/collections4/properties/AbstractPropertiesFactoryTest.java @@ -17,15 +17,20 @@ package org.apache.commons.collections4.properties; +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 java.io.BufferedReader; import java.io.FileInputStream; +import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Properties; + import org.apache.commons.collections4.BulkTest; -import org.junit.Assert; -import org.junit.Assume; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; @@ -52,17 +57,17 @@ protected AbstractPropertiesFactoryTest(final AbstractPropertiesFactory facto } private void assertContents(final T properties) { - Assert.assertEquals("value1", properties.getProperty("key1")); - Assert.assertEquals("value2", properties.getProperty("key2")); - Assert.assertEquals("value3", properties.getProperty("key3")); - Assert.assertEquals("value4", properties.getProperty("key4")); - Assert.assertEquals("value5", properties.getProperty("key5")); - Assert.assertEquals("value6", properties.getProperty("key6")); - Assert.assertEquals("value7", properties.getProperty("key7")); - Assert.assertEquals("value8", properties.getProperty("key8")); - Assert.assertEquals("value9", properties.getProperty("key9")); - Assert.assertEquals("value10", properties.getProperty("key10")); - Assert.assertEquals("value11", properties.getProperty("key11")); + assertEquals("value1", properties.getProperty("key1")); + assertEquals("value2", properties.getProperty("key2")); + assertEquals("value3", properties.getProperty("key3")); + assertEquals("value4", properties.getProperty("key4")); + assertEquals("value5", properties.getProperty("key5")); + assertEquals("value6", properties.getProperty("key6")); + assertEquals("value7", properties.getProperty("key7")); + assertEquals("value8", properties.getProperty("key8")); + assertEquals("value9", properties.getProperty("key9")); + assertEquals("value10", properties.getProperty("key10")); + assertEquals("value11", properties.getProperty("key11")); } private boolean isXmlTest() { @@ -71,12 +76,12 @@ private boolean isXmlTest() { @Test public void testInstance() { - Assert.assertNotNull(PropertiesFactory.INSTANCE); + assertNotNull(PropertiesFactory.INSTANCE); } @Test public void testLoadClassLoaderMissingResource() throws Exception { - Assert.assertNull(factory.load(ClassLoader.getSystemClassLoader(), "missing/test" + fileExtension)); + assertNull(factory.load(ClassLoader.getSystemClassLoader(), "missing/test" + fileExtension)); } @Test @@ -97,13 +102,23 @@ public void testLoadFileName() throws Exception { @Test public void testLoadInputStream() throws Exception { // Can't tell what we are reading - Assume.assumeFalse(isXmlTest()); + if (isXmlTest()) { + return; + } + assertFalse(isXmlTest()); // try (FileInputStream inputStream = new FileInputStream(pathString)) { assertContents(factory.load(inputStream)); } } + @Test + public void testLoadNullInputStream() throws Exception { + //Test load null + final InputStream inputStream = null; + assertNull(factory.load(inputStream)); + } + @Test public void testLoadPath() throws Exception { assertContents(factory.load(Paths.get(pathString))); @@ -112,7 +127,10 @@ public void testLoadPath() throws Exception { @Test public void testLoadReader() throws Exception { // Can't tell what we are reading - Assume.assumeFalse(isXmlTest()); + if (isXmlTest()) { + return; + } + assertFalse(isXmlTest()); // try (BufferedReader inputStream = Files.newBufferedReader(Paths.get(pathString))) { assertContents(factory.load(inputStream)); diff --git a/src/test/java/org/apache/commons/collections4/properties/EmptyPropertiesTest.java b/src/test/java/org/apache/commons/collections4/properties/EmptyPropertiesTest.java index ff690c78be..e49864f73c 100644 --- a/src/test/java/org/apache/commons/collections4/properties/EmptyPropertiesTest.java +++ b/src/test/java/org/apache/commons/collections4/properties/EmptyPropertiesTest.java @@ -17,6 +17,15 @@ package org.apache.commons.collections4.properties; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.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; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -28,121 +37,137 @@ import org.apache.commons.io.input.NullReader; import org.apache.commons.lang3.ArrayUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class EmptyPropertiesTest { @Test public void testClear() { PropertiesFactory.EMPTY_PROPERTIES.clear(); - Assert.assertEquals(0, PropertiesFactory.EMPTY_PROPERTIES.size()); + assertEquals(0, PropertiesFactory.EMPTY_PROPERTIES.size()); } @Test public void testClone() { // TODO Better test? PropertiesFactory.EMPTY_PROPERTIES.clone(); - Assert.assertEquals(0, PropertiesFactory.EMPTY_PROPERTIES.size()); + assertEquals(0, PropertiesFactory.EMPTY_PROPERTIES.size()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testCompute() { - PropertiesFactory.EMPTY_PROPERTIES.compute("key", (k, v) -> "foo"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.compute("key", (k, v) -> "foo"); + }); + assertNull(exception.getMessage()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testComputeIfAbsent() { - PropertiesFactory.EMPTY_PROPERTIES.computeIfAbsent("key", k -> "foo"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.computeIfAbsent("key", k -> "foo"); + }); + assertNull(exception.getMessage()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testComputeIfPresent() { - PropertiesFactory.EMPTY_PROPERTIES.computeIfPresent("key", (k, v) -> "foo"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.computeIfPresent("key", (k, v) -> "foo"); + }); + assertNull(exception.getMessage()); } @Test public void testContains() { - Assert.assertFalse(PropertiesFactory.EMPTY_PROPERTIES.contains("foo")); + assertFalse(PropertiesFactory.EMPTY_PROPERTIES.contains("foo")); } @Test public void testContainsKey() { - Assert.assertFalse(PropertiesFactory.EMPTY_PROPERTIES.containsKey("foo")); + assertFalse(PropertiesFactory.EMPTY_PROPERTIES.containsKey("foo")); } @Test public void testContainsValue() { - Assert.assertFalse(PropertiesFactory.EMPTY_PROPERTIES.containsValue("foo")); + assertFalse(PropertiesFactory.EMPTY_PROPERTIES.containsValue("foo")); } @Test public void testElements() { - Assert.assertFalse(PropertiesFactory.EMPTY_PROPERTIES.elements().hasMoreElements()); + assertFalse(PropertiesFactory.EMPTY_PROPERTIES.elements().hasMoreElements()); } @Test public void testEntrySet() { - Assert.assertTrue(PropertiesFactory.EMPTY_PROPERTIES.entrySet().isEmpty()); + assertTrue(PropertiesFactory.EMPTY_PROPERTIES.entrySet().isEmpty()); } @Test public void testEquals() { - Assert.assertTrue(PropertiesFactory.EMPTY_PROPERTIES.equals(PropertiesFactory.EMPTY_PROPERTIES)); - Assert.assertTrue(PropertiesFactory.EMPTY_PROPERTIES.equals(new Properties())); - Assert.assertTrue(new Properties().equals(PropertiesFactory.EMPTY_PROPERTIES)); - Assert.assertFalse(PropertiesFactory.EMPTY_PROPERTIES.equals(null)); + assertTrue(PropertiesFactory.EMPTY_PROPERTIES.equals(PropertiesFactory.EMPTY_PROPERTIES)); + assertTrue(PropertiesFactory.EMPTY_PROPERTIES.equals(new Properties())); + assertTrue(new Properties().equals(PropertiesFactory.EMPTY_PROPERTIES)); + assertNotEquals(PropertiesFactory.EMPTY_PROPERTIES, null); final Properties p = new Properties(); p.put("Key", "Value"); - Assert.assertFalse(PropertiesFactory.EMPTY_PROPERTIES.equals(p)); - Assert.assertFalse(p.equals(PropertiesFactory.EMPTY_PROPERTIES)); + assertFalse(PropertiesFactory.EMPTY_PROPERTIES.equals(p)); + assertFalse(p.equals(PropertiesFactory.EMPTY_PROPERTIES)); } + @Test public void testForEach() { - PropertiesFactory.EMPTY_PROPERTIES.forEach((k, v) -> Assert.fail()); + PropertiesFactory.EMPTY_PROPERTIES.forEach((k, v) -> fail()); } + @Test + public void testForEachWithNull() { + Exception exception = assertThrows(NullPointerException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.forEach(null); + }); + assertNull(exception.getMessage()); + } @Test public void testGet() { - Assert.assertNull(PropertiesFactory.EMPTY_PROPERTIES.get("foo")); + assertNull(PropertiesFactory.EMPTY_PROPERTIES.get("foo")); } @Test public void testGetOrDefault() { - Assert.assertEquals("bar", PropertiesFactory.EMPTY_PROPERTIES.getOrDefault("foo", "bar")); + assertEquals("bar", PropertiesFactory.EMPTY_PROPERTIES.getOrDefault("foo", "bar")); } @Test public void testGetProperty() { - Assert.assertNull(PropertiesFactory.EMPTY_PROPERTIES.getProperty("foo")); + assertNull(PropertiesFactory.EMPTY_PROPERTIES.getProperty("foo")); } @Test public void testGetPropertyDefault() { - Assert.assertEquals("bar", PropertiesFactory.EMPTY_PROPERTIES.getProperty("foo", "bar")); + assertEquals("bar", PropertiesFactory.EMPTY_PROPERTIES.getProperty("foo", "bar")); } @Test public void testHashCode() { - Assert.assertEquals(PropertiesFactory.EMPTY_PROPERTIES.hashCode(), + assertEquals(PropertiesFactory.EMPTY_PROPERTIES.hashCode(), PropertiesFactory.EMPTY_PROPERTIES.hashCode()); // Should be equals? - // Assert.assertEquals(PropertiesFactory.EMPTY_PROPERTIES.hashCode(), new Properties().hashCode()); + // assertEquals(PropertiesFactory.EMPTY_PROPERTIES.hashCode(), new Properties().hashCode()); } @Test public void testIsEmpty() { - Assert.assertTrue(PropertiesFactory.EMPTY_PROPERTIES.isEmpty()); + assertTrue(PropertiesFactory.EMPTY_PROPERTIES.isEmpty()); } @Test public void testKeys() { - Assert.assertFalse(PropertiesFactory.EMPTY_PROPERTIES.keys().hasMoreElements()); + assertFalse(PropertiesFactory.EMPTY_PROPERTIES.keys().hasMoreElements()); } @Test public void testKeySet() { - Assert.assertTrue(PropertiesFactory.EMPTY_PROPERTIES.keySet().isEmpty()); + assertTrue(PropertiesFactory.EMPTY_PROPERTIES.keySet().isEmpty()); } @Test @@ -153,10 +178,10 @@ public void testListToPrintStream() { // expected final ByteArrayOutputStream expected = new ByteArrayOutputStream(); PropertiesFactory.INSTANCE.createProperties().list(new PrintStream(expected)); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); expected.reset(); new Properties().list(new PrintStream(expected)); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); } @Test @@ -167,83 +192,119 @@ public void testListToPrintWriter() { // expected final ByteArrayOutputStream expected = new ByteArrayOutputStream(); PropertiesFactory.INSTANCE.createProperties().list(new PrintWriter(expected)); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); expected.reset(); new Properties().list(new PrintWriter(expected)); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testLoadFromXML() throws IOException { - PropertiesFactory.EMPTY_PROPERTIES.loadFromXML(new ByteArrayInputStream(ArrayUtils.EMPTY_BYTE_ARRAY)); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.loadFromXML(new ByteArrayInputStream(ArrayUtils.EMPTY_BYTE_ARRAY)); + }); + assertNull(exception.getMessage()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testLoadInputStream() throws IOException { - PropertiesFactory.EMPTY_PROPERTIES.load(new ByteArrayInputStream(ArrayUtils.EMPTY_BYTE_ARRAY)); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.load(new ByteArrayInputStream(ArrayUtils.EMPTY_BYTE_ARRAY)); + }); + assertNull(exception.getMessage()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testLoadReader() throws IOException { try (NullReader reader = new NullReader(0)) { - PropertiesFactory.EMPTY_PROPERTIES.load(reader); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.load(reader); + }); + assertNull(exception.getMessage()); } } - @Test(expected = UnsupportedOperationException.class) + @Test public void testMerge() { - PropertiesFactory.EMPTY_PROPERTIES.merge("key", "value", (k, v) -> "foo"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.merge("key", "value", (k, v) -> "foo"); + }); + assertNull(exception.getMessage()); } @Test public void testPropertyName() { - Assert.assertFalse(PropertiesFactory.EMPTY_PROPERTIES.propertyNames().hasMoreElements()); + assertFalse(PropertiesFactory.EMPTY_PROPERTIES.propertyNames().hasMoreElements()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testPut() { - PropertiesFactory.EMPTY_PROPERTIES.put("Key", "Value"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.put("Key", "Value"); + }); + assertNull(exception.getMessage()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testPutAll() { - PropertiesFactory.EMPTY_PROPERTIES.putAll(new HashMap<>()); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.putAll(new HashMap<>()); + }); + assertNull(exception.getMessage()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testPutIfAbsent() { - PropertiesFactory.EMPTY_PROPERTIES.putIfAbsent("Key", "Value"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.putIfAbsent("Key", "Value"); + }); + assertNull(exception.getMessage()); } @Test public void testRehash() { // Can't really test without extending and casting to a currently private class - // PropertiesFactory.EMPTY_PROPERTIES.rehash(); + //PropertiesFactory.EMPTY_PROPERTIES.rehash(); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testRemove() { - PropertiesFactory.EMPTY_PROPERTIES.remove("key", "value"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.remove("key", "value"); + }); + assertNull(exception.getMessage()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testRemoveKey() { - PropertiesFactory.EMPTY_PROPERTIES.remove("key"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.remove("key"); + }); + assertNull(exception.getMessage()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testReplace() { - PropertiesFactory.EMPTY_PROPERTIES.replace("key", "value1"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.replace("key", "value1"); + }); + assertNull(exception.getMessage()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testReplaceAll() { - PropertiesFactory.EMPTY_PROPERTIES.replaceAll((k, v) -> "value1"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.replaceAll((k, v) -> "value1"); + }); + assertNull(exception.getMessage()); } - @Test(expected = UnsupportedOperationException.class) + @Test public void testReplaceOldValue() { - PropertiesFactory.EMPTY_PROPERTIES.replace("key", "value1", "value2"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.replace("key", "value1", "value2"); + }); + assertNull(exception.getMessage()); } @Test @@ -259,24 +320,27 @@ public void testSave() throws IOException { try (PrintStream out = new PrintStream(expected)) { PropertiesFactory.INSTANCE.createProperties().save(out, comments); } - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); expected.reset(); try (PrintStream out = new PrintStream(expected)) { new Properties().save(out, comments); } - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); } } } - @Test(expected = UnsupportedOperationException.class) + @Test public void testSetProperty() { - PropertiesFactory.EMPTY_PROPERTIES.setProperty("Key", "Value"); + Exception exception = assertThrows(UnsupportedOperationException.class, () -> { + PropertiesFactory.EMPTY_PROPERTIES.setProperty("Key", "Value"); + }); + assertNull(exception.getMessage()); } @Test public void testSize() { - Assert.assertEquals(0, PropertiesFactory.EMPTY_PROPERTIES.size()); + assertEquals(0, PropertiesFactory.EMPTY_PROPERTIES.size()); } @Test @@ -288,10 +352,10 @@ public void testStoreToOutputStream() throws IOException { // expected final ByteArrayOutputStream expected = new ByteArrayOutputStream(); PropertiesFactory.INSTANCE.createProperties().store(new PrintStream(expected), comments); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); expected.reset(); new Properties().store(new PrintStream(expected), comments); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); } @Test @@ -303,10 +367,10 @@ public void testStoreToPrintWriter() throws IOException { // expected final ByteArrayOutputStream expected = new ByteArrayOutputStream(); PropertiesFactory.INSTANCE.createProperties().store(new PrintWriter(expected), comments); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); expected.reset(); new Properties().store(new PrintWriter(expected), comments); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); } @Test @@ -318,10 +382,10 @@ public void testStoreToXMLOutputStream() throws IOException { // expected final ByteArrayOutputStream expected = new ByteArrayOutputStream(); PropertiesFactory.INSTANCE.createProperties().storeToXML(new PrintStream(expected), comments); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); expected.reset(); new Properties().storeToXML(new PrintStream(expected), comments); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); } @Test @@ -334,24 +398,24 @@ public void testStoreToXMLOutputStreamWithEncoding() throws IOException { // expected final ByteArrayOutputStream expected = new ByteArrayOutputStream(); PropertiesFactory.INSTANCE.createProperties().storeToXML(new PrintStream(expected), comments, encoding); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); expected.reset(); new Properties().storeToXML(new PrintStream(expected), comments, encoding); - Assert.assertArrayEquals(expected.toByteArray(), actual.toByteArray()); + assertArrayEquals(expected.toByteArray(), actual.toByteArray()); } @Test public void testStringPropertyName() { - Assert.assertTrue(PropertiesFactory.EMPTY_PROPERTIES.stringPropertyNames().isEmpty()); + assertTrue(PropertiesFactory.EMPTY_PROPERTIES.stringPropertyNames().isEmpty()); } @Test public void testToString() { - Assert.assertEquals(new Properties().toString(), PropertiesFactory.EMPTY_PROPERTIES.toString()); + assertEquals(new Properties().toString(), PropertiesFactory.EMPTY_PROPERTIES.toString()); } @Test public void testValues() { - Assert.assertTrue(PropertiesFactory.EMPTY_PROPERTIES.values().isEmpty()); + assertTrue(PropertiesFactory.EMPTY_PROPERTIES.values().isEmpty()); } } diff --git a/src/test/java/org/apache/commons/collections4/properties/PropertiesFactoryTest.java b/src/test/java/org/apache/commons/collections4/properties/PropertiesFactoryTest.java index ddfe40aacb..510f5bb5da 100644 --- a/src/test/java/org/apache/commons/collections4/properties/PropertiesFactoryTest.java +++ b/src/test/java/org/apache/commons/collections4/properties/PropertiesFactoryTest.java @@ -17,11 +17,12 @@ package org.apache.commons.collections4.properties; -import java.util.Properties; +import static org.junit.jupiter.api.Assertions.assertNotNull; -import org.junit.Assert; +import java.util.Properties; import org.junit.Test; + public class PropertiesFactoryTest extends AbstractPropertiesFactoryTest { public PropertiesFactoryTest(final String fileExtension) { @@ -31,6 +32,6 @@ public PropertiesFactoryTest(final String fileExtension) { @Override @Test public void testInstance() { - Assert.assertNotNull(PropertiesFactory.INSTANCE); + assertNotNull(PropertiesFactory.INSTANCE); } } diff --git a/src/test/java/org/apache/commons/collections4/properties/SortedPropertiesFactoryTest.java b/src/test/java/org/apache/commons/collections4/properties/SortedPropertiesFactoryTest.java index 8f81612eeb..a01ffe6c86 100644 --- a/src/test/java/org/apache/commons/collections4/properties/SortedPropertiesFactoryTest.java +++ b/src/test/java/org/apache/commons/collections4/properties/SortedPropertiesFactoryTest.java @@ -17,7 +17,8 @@ package org.apache.commons.collections4.properties; -import org.junit.Assert; +import static org.junit.jupiter.api.Assertions.assertNotNull; + import org.junit.Test; public class SortedPropertiesFactoryTest extends AbstractPropertiesFactoryTest { @@ -29,6 +30,6 @@ public SortedPropertiesFactoryTest(final String fileExtension) { @Override @Test public void testInstance() { - Assert.assertNotNull(SortedPropertiesFactory.INSTANCE); + assertNotNull(SortedPropertiesFactory.INSTANCE); } } diff --git a/src/test/java/org/apache/commons/collections4/properties/SortedPropertiesTest.java b/src/test/java/org/apache/commons/collections4/properties/SortedPropertiesTest.java index ce294bf886..d58fbcf321 100644 --- a/src/test/java/org/apache/commons/collections4/properties/SortedPropertiesTest.java +++ b/src/test/java/org/apache/commons/collections4/properties/SortedPropertiesTest.java @@ -17,10 +17,11 @@ package org.apache.commons.collections4.properties; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Enumeration; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class SortedPropertiesTest { @@ -32,7 +33,7 @@ public void testKeys() { } final Enumeration keys = sortedProperties.keys(); for (char ch = 'A'; ch <= 'Z'; ch++) { - Assert.assertEquals(String.valueOf(ch), keys.nextElement()); + assertEquals(String.valueOf(ch), keys.nextElement()); } } } 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 e2eaaabc08..1f25601125 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,11 @@ 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()) { + assertTrue(exception.getMessage().contains("queue is empty")); } resetFull(); @@ -200,11 +204,11 @@ 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()) { + assertTrue(exception.getMessage().contains("queue is empty")); } } @@ -253,11 +257,11 @@ 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()) { + assertTrue(exception.getMessage().contains("queue is empty")); } resetFull(); @@ -270,11 +274,11 @@ 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()) { + 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/SynchronizedQueueTest.java b/src/test/java/org/apache/commons/collections4/queue/SynchronizedQueueTest.java index 898291e1ee..5300c7edc4 100644 --- a/src/test/java/org/apache/commons/collections4/queue/SynchronizedQueueTest.java +++ b/src/test/java/org/apache/commons/collections4/queue/SynchronizedQueueTest.java @@ -20,7 +20,7 @@ import java.util.Queue; import org.apache.commons.collections4.BulkTest; -import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; import junit.framework.Test; @@ -51,7 +51,7 @@ public Queue makeObject() { return SynchronizedQueue.synchronizedQueue(new LinkedList()); } - @Ignore("Run once") + @Disabled("Run once") public void testCreate() throws Exception { Queue queue = makeObject(); writeExternalFormToDisk((java.io.Serializable) queue, 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/sequence/SequencesComparatorTest.java b/src/test/java/org/apache/commons/collections4/sequence/SequencesComparatorTest.java index 88bb25af01..0555280057 100644 --- a/src/test/java/org/apache/commons/collections4/sequence/SequencesComparatorTest.java +++ b/src/test/java/org/apache/commons/collections4/sequence/SequencesComparatorTest.java @@ -16,15 +16,17 @@ */ package org.apache.commons.collections4.sequence; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class SequencesComparatorTest { @@ -38,7 +40,7 @@ public void testLength() { final SequencesComparator comparator = new SequencesComparator<>(sequence(before.get(i)), sequence(after.get(i))); - Assert.assertEquals(length[i], comparator.getScript().getModifications()); + assertEquals(length[i], comparator.getScript().getModifications()); } } @@ -49,7 +51,7 @@ public void testExecution() { ev.setList(sequence(before.get(i))); new SequencesComparator<>(sequence(before.get(i)), sequence(after.get(i))).getScript().visit(ev); - Assert.assertEquals(after.get(i), ev.getString()); + assertEquals(after.get(i), ev.getString()); } } @@ -100,7 +102,7 @@ public void testMinimal() { final SequencesComparator comparator = new SequencesComparator<>(sentenceBefore, sentenceAfter); - Assert.assertTrue(comparator.getScript().getModifications() <= nbCom); + assertTrue(comparator.getScript().getModifications() <= nbCom); } } @@ -139,7 +141,7 @@ public void testShadok() { for (final String s : shadokSentence) { concat.append(s); } - Assert.assertEquals(concat.toString(), ev.getString()); + assertEquals(concat.toString(), ev.getString()); } } } @@ -187,7 +189,7 @@ public String getString() { } - @Before + @BeforeEach public void setUp() { before = Arrays.asList( @@ -226,7 +228,7 @@ public void setUp() { } - @After + @AfterEach public void tearDown() { before = null; after = null; 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 adb041f8ad..e26e1d1cfa 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; @@ -67,20 +71,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") @@ -91,22 +93,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/PatriciaTrieTest.java b/src/test/java/org/apache/commons/collections4/trie/PatriciaTrieTest.java index 10a5ad961d..7af3cafc99 100755 --- a/src/test/java/org/apache/commons/collections4/trie/PatriciaTrieTest.java +++ b/src/test/java/org/apache/commons/collections4/trie/PatriciaTrieTest.java @@ -16,6 +16,14 @@ */ package org.apache.commons.collections4.trie; +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.Arrays; import java.util.ConcurrentModificationException; @@ -31,7 +39,6 @@ import org.apache.commons.collections4.BulkTest; import org.apache.commons.collections4.Trie; import org.apache.commons.collections4.map.AbstractSortedMapTest; -import org.junit.Assert; /** * JUnit tests for the PatriciaTrie. @@ -81,210 +88,210 @@ public void testPrefixMap() { Map.Entry entry; map = trie.prefixMap("Al"); - Assert.assertEquals(8, map.size()); - Assert.assertEquals("Alabama", map.firstKey()); - Assert.assertEquals("Alliese", map.lastKey()); - Assert.assertEquals("Albertoo", map.get("Albertoo")); - Assert.assertNotNull(trie.get("Xavier")); - Assert.assertNull(map.get("Xavier")); - Assert.assertNull(trie.get("Alice")); - Assert.assertNull(map.get("Alice")); + assertEquals(8, map.size()); + assertEquals("Alabama", map.firstKey()); + assertEquals("Alliese", map.lastKey()); + assertEquals("Albertoo", map.get("Albertoo")); + assertNotNull(trie.get("Xavier")); + assertNull(map.get("Xavier")); + assertNull(trie.get("Alice")); + assertNull(map.get("Alice")); iterator = map.values().iterator(); - Assert.assertEquals("Alabama", iterator.next()); - Assert.assertEquals("Albert", iterator.next()); - Assert.assertEquals("Alberto", iterator.next()); - Assert.assertEquals("Albertoo", iterator.next()); - Assert.assertEquals("Alberts", iterator.next()); - Assert.assertEquals("Alien", iterator.next()); - Assert.assertEquals("Allie", iterator.next()); - Assert.assertEquals("Alliese", iterator.next()); - Assert.assertFalse(iterator.hasNext()); + assertEquals("Alabama", iterator.next()); + assertEquals("Albert", iterator.next()); + assertEquals("Alberto", iterator.next()); + assertEquals("Albertoo", iterator.next()); + assertEquals("Alberts", iterator.next()); + assertEquals("Alien", iterator.next()); + assertEquals("Allie", iterator.next()); + assertEquals("Alliese", iterator.next()); + assertFalse(iterator.hasNext()); map = trie.prefixMap("Albert"); iterator = map.keySet().iterator(); - Assert.assertEquals("Albert", iterator.next()); - Assert.assertEquals("Alberto", iterator.next()); - Assert.assertEquals("Albertoo", iterator.next()); - Assert.assertEquals("Alberts", iterator.next()); - Assert.assertFalse(iterator.hasNext()); - Assert.assertEquals(4, map.size()); - Assert.assertEquals("Albert", map.firstKey()); - Assert.assertEquals("Alberts", map.lastKey()); - Assert.assertNull(trie.get("Albertz")); + assertEquals("Albert", iterator.next()); + assertEquals("Alberto", iterator.next()); + assertEquals("Albertoo", iterator.next()); + assertEquals("Alberts", iterator.next()); + assertFalse(iterator.hasNext()); + assertEquals(4, map.size()); + assertEquals("Albert", map.firstKey()); + assertEquals("Alberts", map.lastKey()); + assertNull(trie.get("Albertz")); map.put("Albertz", "Albertz"); - Assert.assertEquals("Albertz", trie.get("Albertz")); - Assert.assertEquals(5, map.size()); - Assert.assertEquals("Albertz", map.lastKey()); + assertEquals("Albertz", trie.get("Albertz")); + assertEquals(5, map.size()); + assertEquals("Albertz", map.lastKey()); iterator = map.keySet().iterator(); - Assert.assertEquals("Albert", iterator.next()); - Assert.assertEquals("Alberto", iterator.next()); - Assert.assertEquals("Albertoo", iterator.next()); - Assert.assertEquals("Alberts", iterator.next()); - Assert.assertEquals("Albertz", iterator.next()); - Assert.assertFalse(iterator.hasNext()); - Assert.assertEquals("Albertz", map.remove("Albertz")); + assertEquals("Albert", iterator.next()); + assertEquals("Alberto", iterator.next()); + assertEquals("Albertoo", iterator.next()); + assertEquals("Alberts", iterator.next()); + assertEquals("Albertz", iterator.next()); + assertFalse(iterator.hasNext()); + assertEquals("Albertz", map.remove("Albertz")); map = trie.prefixMap("Alberto"); - Assert.assertEquals(2, map.size()); - Assert.assertEquals("Alberto", map.firstKey()); - Assert.assertEquals("Albertoo", map.lastKey()); + assertEquals(2, map.size()); + assertEquals("Alberto", map.firstKey()); + assertEquals("Albertoo", map.lastKey()); entryIterator = map.entrySet().iterator(); entry = entryIterator.next(); - Assert.assertEquals("Alberto", entry.getKey()); - Assert.assertEquals("Alberto", entry.getValue()); + assertEquals("Alberto", entry.getKey()); + assertEquals("Alberto", entry.getValue()); entry = entryIterator.next(); - Assert.assertEquals("Albertoo", entry.getKey()); - Assert.assertEquals("Albertoo", entry.getValue()); - Assert.assertFalse(entryIterator.hasNext()); + assertEquals("Albertoo", entry.getKey()); + assertEquals("Albertoo", entry.getValue()); + assertFalse(entryIterator.hasNext()); trie.put("Albertoad", "Albertoad"); - Assert.assertEquals(3, map.size()); - Assert.assertEquals("Alberto", map.firstKey()); - Assert.assertEquals("Albertoo", map.lastKey()); + assertEquals(3, map.size()); + assertEquals("Alberto", map.firstKey()); + assertEquals("Albertoo", map.lastKey()); entryIterator = map.entrySet().iterator(); entry = entryIterator.next(); - Assert.assertEquals("Alberto", entry.getKey()); - Assert.assertEquals("Alberto", entry.getValue()); + assertEquals("Alberto", entry.getKey()); + assertEquals("Alberto", entry.getValue()); entry = entryIterator.next(); - Assert.assertEquals("Albertoad", entry.getKey()); - Assert.assertEquals("Albertoad", entry.getValue()); + assertEquals("Albertoad", entry.getKey()); + assertEquals("Albertoad", entry.getValue()); entry = entryIterator.next(); - Assert.assertEquals("Albertoo", entry.getKey()); - Assert.assertEquals("Albertoo", entry.getValue()); - Assert.assertFalse(entryIterator.hasNext()); - Assert.assertEquals("Albertoo", trie.remove("Albertoo")); - Assert.assertEquals("Alberto", map.firstKey()); - Assert.assertEquals("Albertoad", map.lastKey()); - Assert.assertEquals(2, map.size()); + assertEquals("Albertoo", entry.getKey()); + assertEquals("Albertoo", entry.getValue()); + assertFalse(entryIterator.hasNext()); + assertEquals("Albertoo", trie.remove("Albertoo")); + assertEquals("Alberto", map.firstKey()); + assertEquals("Albertoad", map.lastKey()); + assertEquals(2, map.size()); entryIterator = map.entrySet().iterator(); entry = entryIterator.next(); - Assert.assertEquals("Alberto", entry.getKey()); - Assert.assertEquals("Alberto", entry.getValue()); + assertEquals("Alberto", entry.getKey()); + assertEquals("Alberto", entry.getValue()); entry = entryIterator.next(); - Assert.assertEquals("Albertoad", entry.getKey()); - Assert.assertEquals("Albertoad", entry.getValue()); - Assert.assertFalse(entryIterator.hasNext()); - Assert.assertEquals("Albertoad", trie.remove("Albertoad")); + assertEquals("Albertoad", entry.getKey()); + assertEquals("Albertoad", entry.getValue()); + assertFalse(entryIterator.hasNext()); + assertEquals("Albertoad", trie.remove("Albertoad")); trie.put("Albertoo", "Albertoo"); map = trie.prefixMap("X"); - Assert.assertEquals(2, map.size()); - Assert.assertFalse(map.containsKey("Albert")); - Assert.assertTrue(map.containsKey("Xavier")); - Assert.assertFalse(map.containsKey("Xalan")); + assertEquals(2, map.size()); + assertFalse(map.containsKey("Albert")); + assertTrue(map.containsKey("Xavier")); + assertFalse(map.containsKey("Xalan")); iterator = map.values().iterator(); - Assert.assertEquals("Xavier", iterator.next()); - Assert.assertEquals("XyZ", iterator.next()); - Assert.assertFalse(iterator.hasNext()); + assertEquals("Xavier", iterator.next()); + assertEquals("XyZ", iterator.next()); + assertFalse(iterator.hasNext()); map = trie.prefixMap("An"); - Assert.assertEquals(1, map.size()); - Assert.assertEquals("Anna", map.firstKey()); - Assert.assertEquals("Anna", map.lastKey()); + assertEquals(1, map.size()); + assertEquals("Anna", map.firstKey()); + assertEquals("Anna", map.lastKey()); iterator = map.keySet().iterator(); - Assert.assertEquals("Anna", iterator.next()); - Assert.assertFalse(iterator.hasNext()); + assertEquals("Anna", iterator.next()); + assertFalse(iterator.hasNext()); map = trie.prefixMap("Ban"); - Assert.assertEquals(1, map.size()); - Assert.assertEquals("Banane", map.firstKey()); - Assert.assertEquals("Banane", map.lastKey()); + assertEquals(1, map.size()); + assertEquals("Banane", map.firstKey()); + assertEquals("Banane", map.lastKey()); iterator = map.keySet().iterator(); - Assert.assertEquals("Banane", iterator.next()); - Assert.assertFalse(iterator.hasNext()); + assertEquals("Banane", iterator.next()); + assertFalse(iterator.hasNext()); map = trie.prefixMap("Am"); - Assert.assertFalse(map.isEmpty()); - Assert.assertEquals(3, map.size()); - Assert.assertEquals("Amber", trie.remove("Amber")); - iterator = map.keySet().iterator(); - Assert.assertEquals("Amma", iterator.next()); - Assert.assertEquals("Ammun", iterator.next()); - Assert.assertFalse(iterator.hasNext()); + assertFalse(map.isEmpty()); + assertEquals(3, map.size()); + assertEquals("Amber", trie.remove("Amber")); iterator = map.keySet().iterator(); + assertEquals("Amma", iterator.next()); + assertEquals("Ammun", iterator.next()); + assertFalse(iterator.hasNext()); + final Iterator iterator1 = map.keySet().iterator(); map.put("Amber", "Amber"); - Assert.assertEquals(3, map.size()); - try { - iterator.next(); - Assert.fail("CME expected"); - } catch(final ConcurrentModificationException expected) {} - Assert.assertEquals("Amber", map.firstKey()); - Assert.assertEquals("Ammun", map.lastKey()); + assertEquals(3, map.size()); + Exception exception = assertThrows(ConcurrentModificationException.class, () -> { + iterator1.next(); + }); + assertNull(exception.getMessage()); + assertEquals("Amber", map.firstKey()); + assertEquals("Ammun", map.lastKey()); map = trie.prefixMap("Ak\0"); - Assert.assertTrue(map.isEmpty()); + assertTrue(map.isEmpty()); map = trie.prefixMap("Ak"); - Assert.assertEquals(2, map.size()); - Assert.assertEquals("Akka", map.firstKey()); - Assert.assertEquals("Akko", map.lastKey()); + assertEquals(2, map.size()); + assertEquals("Akka", map.firstKey()); + assertEquals("Akko", map.lastKey()); map.put("Ak", "Ak"); - Assert.assertEquals("Ak", map.firstKey()); - Assert.assertEquals("Akko", map.lastKey()); - Assert.assertEquals(3, map.size()); + assertEquals("Ak", map.firstKey()); + assertEquals("Akko", map.lastKey()); + assertEquals(3, map.size()); trie.put("Al", "Al"); - Assert.assertEquals(3, map.size()); - Assert.assertEquals("Ak", map.remove("Ak")); - Assert.assertEquals("Akka", map.firstKey()); - Assert.assertEquals("Akko", map.lastKey()); - Assert.assertEquals(2, map.size()); + assertEquals(3, map.size()); + assertEquals("Ak", map.remove("Ak")); + assertEquals("Akka", map.firstKey()); + assertEquals("Akko", map.lastKey()); + assertEquals(2, map.size()); iterator = map.keySet().iterator(); - Assert.assertEquals("Akka", iterator.next()); - Assert.assertEquals("Akko", iterator.next()); - Assert.assertFalse(iterator.hasNext()); - Assert.assertEquals("Al", trie.remove("Al")); + assertEquals("Akka", iterator.next()); + assertEquals("Akko", iterator.next()); + assertFalse(iterator.hasNext()); + assertEquals("Al", trie.remove("Al")); map = trie.prefixMap("Akka"); - Assert.assertEquals(1, map.size()); - Assert.assertEquals("Akka", map.firstKey()); - Assert.assertEquals("Akka", map.lastKey()); + assertEquals(1, map.size()); + assertEquals("Akka", map.firstKey()); + assertEquals("Akka", map.lastKey()); iterator = map.keySet().iterator(); - Assert.assertEquals("Akka", iterator.next()); - Assert.assertFalse(iterator.hasNext()); - - map = trie.prefixMap("Ab"); - Assert.assertTrue(map.isEmpty()); - Assert.assertEquals(0, map.size()); - try { - final Object o = map.firstKey(); - Assert.fail("got a first key: " + o); - } catch(final NoSuchElementException nsee) {} - try { - final Object o = map.lastKey(); - Assert.fail("got a last key: " + o); - } catch(final NoSuchElementException nsee) {} - iterator = map.values().iterator(); - Assert.assertFalse(iterator.hasNext()); - - map = trie.prefixMap("Albertooo"); - Assert.assertTrue(map.isEmpty()); - Assert.assertEquals(0, map.size()); - try { - final Object o = map.firstKey(); - Assert.fail("got a first key: " + o); - } catch(final NoSuchElementException nsee) {} - try { - final Object o = map.lastKey(); - Assert.fail("got a last key: " + o); - } catch(final NoSuchElementException nsee) {} - iterator = map.values().iterator(); - Assert.assertFalse(iterator.hasNext()); + assertEquals("Akka", iterator.next()); + assertFalse(iterator.hasNext()); + + final SortedMap map1 = trie.prefixMap("Ab"); + assertTrue(map1.isEmpty()); + assertEquals(0, map1.size()); + exception = assertThrows(NoSuchElementException.class, () -> { + final Object o = map1.firstKey(); + }); + assertNull(exception.getMessage()); + exception = assertThrows(NoSuchElementException.class, () -> { + final Object o = map1.lastKey(); + }); + assertNull(exception.getMessage()); + iterator = map1.values().iterator(); + assertFalse(iterator.hasNext()); + + final SortedMap map2 = trie.prefixMap("Albertooo"); + assertTrue(map2.isEmpty()); + assertEquals(0, map2.size()); + exception = assertThrows(NoSuchElementException.class, () -> { + final Object o = map2.firstKey(); + }); + assertNull(exception.getMessage()); + exception = assertThrows(NoSuchElementException.class, () -> { + final Object o = map2.lastKey(); + }); + assertNull(exception.getMessage()); + iterator = map2.values().iterator(); + assertFalse(iterator.hasNext()); map = trie.prefixMap(""); - Assert.assertSame(trie, map); // stricter than necessary, but a good check - - map = trie.prefixMap("\0"); - Assert.assertTrue(map.isEmpty()); - Assert.assertEquals(0, map.size()); - try { - final Object o = map.firstKey(); - Assert.fail("got a first key: " + o); - } catch(final NoSuchElementException nsee) {} - try { - final Object o = map.lastKey(); - Assert.fail("got a last key: " + o); - } catch(final NoSuchElementException nsee) {} - iterator = map.values().iterator(); - Assert.assertFalse(iterator.hasNext()); + assertSame(trie, map); // stricter than necessary, but a good check + + final SortedMap map3 = trie.prefixMap("\0"); + assertTrue(map3.isEmpty()); + assertEquals(0, map3.size()); + exception = assertThrows(NoSuchElementException.class, () -> { + final Object o = map3.firstKey(); + }); + assertNull(exception.getMessage()); + exception = assertThrows(NoSuchElementException.class, () -> { + final Object o = map3.lastKey(); + }); + assertNull(exception.getMessage()); + iterator = map3.values().iterator(); + assertFalse(iterator.hasNext()); } public void testPrefixMapRemoval() { @@ -302,31 +309,31 @@ public void testPrefixMapRemoval() { } SortedMap map = trie.prefixMap("Al"); - Assert.assertEquals(8, map.size()); + assertEquals(8, map.size()); Iterator iter = map.keySet().iterator(); - Assert.assertEquals("Alabama", iter.next()); - Assert.assertEquals("Albert", iter.next()); - Assert.assertEquals("Alberto", iter.next()); - Assert.assertEquals("Albertoo", iter.next()); - Assert.assertEquals("Alberts", iter.next()); - Assert.assertEquals("Alien", iter.next()); + assertEquals("Alabama", iter.next()); + assertEquals("Albert", iter.next()); + assertEquals("Alberto", iter.next()); + assertEquals("Albertoo", iter.next()); + assertEquals("Alberts", iter.next()); + assertEquals("Alien", iter.next()); iter.remove(); - Assert.assertEquals(7, map.size()); - Assert.assertEquals("Allie", iter.next()); - Assert.assertEquals("Alliese", iter.next()); - Assert.assertFalse(iter.hasNext()); + assertEquals(7, map.size()); + assertEquals("Allie", iter.next()); + assertEquals("Alliese", iter.next()); + assertFalse(iter.hasNext()); map = trie.prefixMap("Ak"); - Assert.assertEquals(2, map.size()); + assertEquals(2, map.size()); iter = map.keySet().iterator(); - Assert.assertEquals("Akka", iter.next()); + assertEquals("Akka", iter.next()); iter.remove(); - Assert.assertEquals(1, map.size()); - Assert.assertEquals("Akko", iter.next()); + assertEquals(1, map.size()); + assertEquals("Akko", iter.next()); if (iter.hasNext()) { - Assert.fail("shouldn't have next (but was: " + iter.next() + ")"); + fail("shouldn't have next (but was: " + iter.next() + ")"); } - Assert.assertFalse(iter.hasNext()); + assertFalse(iter.hasNext()); } public void testPrefixMapSizes() { 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")); } //-----------------------------------------------------------------------