Clean up testing of exceptions

Now that the entire project is ported to JUnit Jupiter, there are more
elegant ways to test for exceptions, which this patch applies
throughtout the code base.

If throwing an exception is supposed to fail a test, just throwing it
outside of the method cleans up the code and makes it more elegant,
instead of catching it and calling Assertions#fail.

If an exception is supposed to be thrown, calling
Assertions#assertThrows is a more elegant option than calling
Assertions#fail in the try block and then catching and ignoring the
expected exception.
Note that assertThrows uses a lambda block, so the variables inside it
should be final or effectively final. Reusing variables is a common
practice in the tests, so where needed new final variables were
introduced, or the variables used were inlined.
This commit is contained in:
Allon Mureinik 2018-10-13 17:08:48 +03:00 committed by pascalschumacher
parent 0fa0bfd8bb
commit 3387734b4f
43 changed files with 1635 additions and 3725 deletions

View File

@ -21,8 +21,8 @@ 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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.Arrays;
@ -40,12 +40,9 @@ public class ArrayUtilsAddTest {
n = ArrayUtils.addAll(new Number[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)});
assertEquals(2,n.length);
assertEquals(Number.class,n.getClass().getComponentType());
try {
// Invalid - can't store Long in Integer array
n = ArrayUtils.addAll(new Integer[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)});
fail("Should have generated IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
}
// Invalid - can't store Long in Integer array
assertThrows(IllegalArgumentException.class,
() -> ArrayUtils.addAll(new Integer[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)}));
}
@Test
@ -226,25 +223,12 @@ public class ArrayUtilsAddTest {
}
@Test
@SuppressWarnings("deprecation")
public void testLANG571(){
final String[] stringArray=null;
final String aString=null;
try {
@SuppressWarnings("unused")
final
String[] sa = ArrayUtils.add(stringArray, aString);
fail("Should have caused IllegalArgumentException");
} catch (final IllegalArgumentException iae){
//expected
}
try {
@SuppressWarnings({ "unused", "deprecation" })
final
String[] sa = ArrayUtils.add(stringArray, 0, aString);
fail("Should have caused IllegalArgumentException");
} catch (final IllegalArgumentException iae){
//expected
}
assertThrows(IllegalArgumentException.class, () -> ArrayUtils.add(stringArray, aString));
assertThrows(IllegalArgumentException.class, () -> ArrayUtils.add(stringArray, 0, aString));
}
@Test
@ -408,36 +392,25 @@ public class ArrayUtilsAddTest {
// boolean tests
boolean[] booleanArray = ArrayUtils.add( null, 0, true );
assertTrue( Arrays.equals( new boolean[] { true }, booleanArray ) );
try {
booleanArray = ArrayUtils.add( null, -1, true );
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
IndexOutOfBoundsException e =
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( null, -1, true));
assertEquals("Index: -1, Length: 0", e.getMessage());
booleanArray = ArrayUtils.add( new boolean[] { true }, 0, false);
assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) );
booleanArray = ArrayUtils.add( new boolean[] { false }, 1, true);
assertTrue( Arrays.equals( new boolean[] { false, true }, booleanArray ) );
booleanArray = ArrayUtils.add( new boolean[] { true, false }, 1, true);
assertTrue( Arrays.equals( new boolean[] { true, true, false }, booleanArray ) );
try {
booleanArray = ArrayUtils.add( new boolean[] { true, false }, 4, true);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
booleanArray = ArrayUtils.add( new boolean[] { true, false }, -1, true);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new boolean[] { true, false }, 4, true));
assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new boolean[] { true, false }, -1, true));
assertEquals("Index: -1, Length: 2", e.getMessage());
// char tests
char[] charArray = ArrayUtils.add( (char[]) null, 0, 'a' );
assertTrue( Arrays.equals( new char[] { 'a' }, charArray ) );
try {
charArray = ArrayUtils.add( (char[]) null, -1, 'a' );
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (char[]) null, -1, 'a' ));
assertEquals("Index: -1, Length: 0", e.getMessage());
charArray = ArrayUtils.add( new char[] { 'a' }, 0, 'b');
assertTrue( Arrays.equals( new char[] { 'b', 'a' }, charArray ) );
charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 0, 'c');
@ -446,166 +419,106 @@ public class ArrayUtilsAddTest {
assertTrue( Arrays.equals( new char[] { 'a', 'k', 'b' }, charArray ) );
charArray = ArrayUtils.add( new char[] { 'a', 'b', 'c' }, 1, 't');
assertTrue( Arrays.equals( new char[] { 'a', 't', 'b', 'c' }, charArray ) );
try {
charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 4, 'c');
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
charArray = ArrayUtils.add( new char[] { 'a', 'b' }, -1, 'c');
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new char[] { 'a', 'b' }, 4, 'c'));
assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new char[] { 'a', 'b' }, -1, 'c'));
assertEquals("Index: -1, Length: 2", e.getMessage());
// short tests
short[] shortArray = ArrayUtils.add( new short[] { 1 }, 0, (short) 2);
assertTrue( Arrays.equals( new short[] { 2, 1 }, shortArray ) );
try {
shortArray = ArrayUtils.add( (short[]) null, -1, (short) 2);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (short[]) null, -1, (short) 2));
assertEquals("Index: -1, Length: 0", e.getMessage());
shortArray = ArrayUtils.add( new short[] { 2, 6 }, 2, (short) 10);
assertTrue( Arrays.equals( new short[] { 2, 6, 10 }, shortArray ) );
shortArray = ArrayUtils.add( new short[] { 2, 6 }, 0, (short) -4);
assertTrue( Arrays.equals( new short[] { -4, 2, 6 }, shortArray ) );
shortArray = ArrayUtils.add( new short[] { 2, 6, 3 }, 2, (short) 1);
assertTrue( Arrays.equals( new short[] { 2, 6, 1, 3 }, shortArray ) );
try {
shortArray = ArrayUtils.add( new short[] { 2, 6 }, 4, (short) 10);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
shortArray = ArrayUtils.add( new short[] { 2, 6 }, -1, (short) 10);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new short[] { 2, 6 }, 4, (short) 10));
assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new short[] { 2, 6 }, -1, (short) 10));
assertEquals("Index: -1, Length: 2", e.getMessage());
// byte tests
byte[] byteArray = ArrayUtils.add( new byte[] { 1 }, 0, (byte) 2);
assertTrue( Arrays.equals( new byte[] { 2, 1 }, byteArray ) );
try {
byteArray = ArrayUtils.add( (byte[]) null, -1, (byte) 2);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (byte[]) null, -1, (byte) 2));
assertEquals("Index: -1, Length: 0", e.getMessage());
byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 2, (byte) 3);
assertTrue( Arrays.equals( new byte[] { 2, 6, 3 }, byteArray ) );
byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 0, (byte) 1);
assertTrue( Arrays.equals( new byte[] { 1, 2, 6 }, byteArray ) );
byteArray = ArrayUtils.add( new byte[] { 2, 6, 3 }, 2, (byte) 1);
assertTrue( Arrays.equals( new byte[] { 2, 6, 1, 3 }, byteArray ) );
try {
byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 4, (byte) 3);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
byteArray = ArrayUtils.add( new byte[] { 2, 6 }, -1, (byte) 3);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new byte[] { 2, 6 }, 4, (byte) 3));
assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new byte[] { 2, 6 }, -1, (byte) 3));
assertEquals("Index: -1, Length: 2", e.getMessage());
// int tests
int[] intArray = ArrayUtils.add( new int[] { 1 }, 0, 2);
assertTrue( Arrays.equals( new int[] { 2, 1 }, intArray ) );
try {
intArray = ArrayUtils.add( (int[]) null, -1, 2);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (int[]) null, -1, 2));
assertEquals("Index: -1, Length: 0", e.getMessage());
intArray = ArrayUtils.add( new int[] { 2, 6 }, 2, 10);
assertTrue( Arrays.equals( new int[] { 2, 6, 10 }, intArray ) );
intArray = ArrayUtils.add( new int[] { 2, 6 }, 0, -4);
assertTrue( Arrays.equals( new int[] { -4, 2, 6 }, intArray ) );
intArray = ArrayUtils.add( new int[] { 2, 6, 3 }, 2, 1);
assertTrue( Arrays.equals( new int[] { 2, 6, 1, 3 }, intArray ) );
try {
intArray = ArrayUtils.add( new int[] { 2, 6 }, 4, 10);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
intArray = ArrayUtils.add( new int[] { 2, 6 }, -1, 10);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new int[] { 2, 6 }, 4, 10));
assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new int[] { 2, 6 }, -1, 10));
assertEquals("Index: -1, Length: 2", e.getMessage());
// long tests
long[] longArray = ArrayUtils.add( new long[] { 1L }, 0, 2L);
assertTrue( Arrays.equals( new long[] { 2L, 1L }, longArray ) );
try {
longArray = ArrayUtils.add( (long[]) null, -1, 2L);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (long[]) null, -1, 2L));
assertEquals("Index: -1, Length: 0", e.getMessage());
longArray = ArrayUtils.add( new long[] { 2L, 6L }, 2, 10L);
assertTrue( Arrays.equals( new long[] { 2L, 6L, 10L }, longArray ) );
longArray = ArrayUtils.add( new long[] { 2L, 6L }, 0, -4L);
assertTrue( Arrays.equals( new long[] { -4L, 2L, 6L }, longArray ) );
longArray = ArrayUtils.add( new long[] { 2L, 6L, 3L }, 2, 1L);
assertTrue( Arrays.equals( new long[] { 2L, 6L, 1L, 3L }, longArray ) );
try {
longArray = ArrayUtils.add( new long[] { 2L, 6L }, 4, 10L);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
longArray = ArrayUtils.add( new long[] { 2L, 6L }, -1, 10L);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new long[] { 2L, 6L }, 4, 10L));
assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new long[] { 2L, 6L }, -1, 10L));
assertEquals("Index: -1, Length: 2", e.getMessage());
// float tests
float[] floatArray = ArrayUtils.add( new float[] { 1.1f }, 0, 2.2f);
assertTrue( Arrays.equals( new float[] { 2.2f, 1.1f }, floatArray ) );
try {
floatArray = ArrayUtils.add( (float[]) null, -1, 2.2f);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (float[]) null, -1, 2.2f));
assertEquals("Index: -1, Length: 0", e.getMessage());
floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 2, 10.5f);
assertTrue( Arrays.equals( new float[] { 2.3f, 6.4f, 10.5f }, floatArray ) );
floatArray = ArrayUtils.add( new float[] { 2.6f, 6.7f }, 0, -4.8f);
assertTrue( Arrays.equals( new float[] { -4.8f, 2.6f, 6.7f }, floatArray ) );
floatArray = ArrayUtils.add( new float[] { 2.9f, 6.0f, 0.3f }, 2, 1.0f);
assertTrue( Arrays.equals( new float[] { 2.9f, 6.0f, 1.0f, 0.3f }, floatArray ) );
try {
floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 4, 10.5f);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, -1, 10.5f);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new float[] { 2.3f, 6.4f }, 4, 10.5f));
assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new float[] { 2.3f, 6.4f }, -1, 10.5f));
assertEquals("Index: -1, Length: 2", e.getMessage());
// double tests
double[] doubleArray = ArrayUtils.add( new double[] { 1.1 }, 0, 2.2);
assertTrue( Arrays.equals( new double[] { 2.2, 1.1 }, doubleArray ) );
try {
doubleArray = ArrayUtils.add(null, -1, 2.2);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 0", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(null, -1, 2.2));
assertEquals("Index: -1, Length: 0", e.getMessage());
doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 2, 10.5);
assertTrue( Arrays.equals( new double[] { 2.3, 6.4, 10.5 }, doubleArray ) );
doubleArray = ArrayUtils.add( new double[] { 2.6, 6.7 }, 0, -4.8);
assertTrue( Arrays.equals( new double[] { -4.8, 2.6, 6.7 }, doubleArray ) );
doubleArray = ArrayUtils.add( new double[] { 2.9, 6.0, 0.3 }, 2, 1.0);
assertTrue( Arrays.equals( new double[] { 2.9, 6.0, 1.0, 0.3 }, doubleArray ) );
try {
doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 4, 10.5);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: 4, Length: 2", e.getMessage());
}
try {
doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, -1, 10.5);
} catch(final IndexOutOfBoundsException e) {
assertEquals("Index: -1, Length: 2", e.getMessage());
}
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new double[] { 2.3, 6.4 }, 4, 10.5));
assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new double[] { 2.3, 6.4 }, -1, 10.5));
assertEquals("Index: -1, Length: 2", e.getMessage());
}
}

View File

@ -20,7 +20,7 @@ package org.apache.commons.lang3;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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 org.junit.jupiter.api.Test;
@ -42,19 +42,8 @@ public class ArrayUtilsInsertTest {
assertArrayEquals(new boolean[0], ArrayUtils.insert(0, new boolean[0], null));
assertNull(ArrayUtils.insert(42, (boolean[]) null, null));
try {
ArrayUtils.insert(-1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
ArrayUtils.insert(array.length + 1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array));
assertArrayEquals(new boolean[]{false,true,false,true}, ArrayUtils.insert(0, array, false));
assertArrayEquals(new boolean[]{true,false,false,true}, ArrayUtils.insert(1, array, false));
@ -78,19 +67,8 @@ public class ArrayUtilsInsertTest {
assertArrayEquals(new byte[0], ArrayUtils.insert(0, new byte[0], null));
assertNull(ArrayUtils.insert(42, (byte[]) null, null));
try {
ArrayUtils.insert(-1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
ArrayUtils.insert(array.length + 1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array));
assertArrayEquals(new byte[]{0,1,2,3}, ArrayUtils.insert(0, array, (byte) 0));
assertArrayEquals(new byte[]{1,0,2,3}, ArrayUtils.insert(1, array, (byte) 0));
@ -113,19 +91,8 @@ public class ArrayUtilsInsertTest {
assertArrayEquals(new char[0], ArrayUtils.insert(0, new char[0], null));
assertNull(ArrayUtils.insert(42, (char[]) null, null));
try {
ArrayUtils.insert(-1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
ArrayUtils.insert(array.length + 1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array));
assertArrayEquals(new char[]{'z','a','b','c'}, ArrayUtils.insert(0, array, 'z'));
assertArrayEquals(new char[]{'a','z','b','c'}, ArrayUtils.insert(1, array, 'z'));
@ -149,19 +116,8 @@ public class ArrayUtilsInsertTest {
assertArrayEquals(new double[0], ArrayUtils.insert(0, new double[0], null), delta);
assertNull(ArrayUtils.insert(42, (double[]) null, null));
try {
ArrayUtils.insert(-1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
ArrayUtils.insert(array.length + 1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array));
assertArrayEquals(new double[]{0,1,2,3}, ArrayUtils.insert(0, array, 0), delta);
assertArrayEquals(new double[]{1,0,2,3}, ArrayUtils.insert(1, array, 0), delta);
@ -185,19 +141,8 @@ public class ArrayUtilsInsertTest {
assertArrayEquals(new float[0], ArrayUtils.insert(0, new float[0], null), delta);
assertNull(ArrayUtils.insert(42, (float[]) null, null));
try {
ArrayUtils.insert(-1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
ArrayUtils.insert(array.length + 1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array));
assertArrayEquals(new float[]{0,1,2,3}, ArrayUtils.insert(0, array, 0), delta);
assertArrayEquals(new float[]{1,0,2,3}, ArrayUtils.insert(1, array, 0), delta);
@ -220,19 +165,8 @@ public class ArrayUtilsInsertTest {
assertArrayEquals(new int[0], ArrayUtils.insert(0, new int[0], null));
assertNull(ArrayUtils.insert(42, (int[]) null, null));
try {
ArrayUtils.insert(-1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
ArrayUtils.insert(array.length + 1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array));
assertArrayEquals(new int[]{0,1,2,3}, ArrayUtils.insert(0, array, 0));
assertArrayEquals(new int[]{1,0,2,3}, ArrayUtils.insert(1, array, 0));
@ -256,19 +190,8 @@ public class ArrayUtilsInsertTest {
assertArrayEquals(new long[0], ArrayUtils.insert(0, new long[0], null));
assertNull(ArrayUtils.insert(42, (long[]) null, null));
try {
ArrayUtils.insert(-1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
ArrayUtils.insert(array.length + 1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array));
assertArrayEquals(new long[]{0,1,2,3}, ArrayUtils.insert(0, array, 0));
assertArrayEquals(new long[]{1,0,2,3}, ArrayUtils.insert(1, array, 0));
@ -292,19 +215,8 @@ public class ArrayUtilsInsertTest {
assertArrayEquals(new short[0], ArrayUtils.insert(0, new short[0], null));
assertNull(ArrayUtils.insert(42, (short[]) null, null));
try {
ArrayUtils.insert(-1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
ArrayUtils.insert(array.length + 1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array));
assertArrayEquals(new short[]{0,1,2,3}, ArrayUtils.insert(0, array, (short) 0));
assertArrayEquals(new short[]{1,0,2,3}, ArrayUtils.insert(1, array, (short) 0));
@ -328,19 +240,8 @@ public class ArrayUtilsInsertTest {
assertArrayEquals(new String[0], ArrayUtils.insert(0, new String[0], (String[]) null));
assertNull(ArrayUtils.insert(42, null, (String[]) null));
try {
ArrayUtils.insert(-1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
ArrayUtils.insert(array.length + 1, array, array);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(-1, array, array));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.insert(array.length + 1, array, array));
assertArrayEquals(new String[]{"z","a","b","c"}, ArrayUtils.insert(0, array, "z"));
assertArrayEquals(new String[]{"a","z","b","c"}, ArrayUtils.insert(1, array, "z"));

View File

@ -19,8 +19,8 @@ package org.apache.commons.lang3;
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 static org.junit.jupiter.api.Assertions.fail;
import java.util.Arrays;
@ -46,18 +46,9 @@ public class ArrayUtilsRemoveTest {
array = ArrayUtils.remove(new Object[] {"a", "b", "c"}, 1);
assertTrue(Arrays.equals(new Object[] {"a", "c"}, array));
assertEquals(Object.class, array.getClass().getComponentType());
try {
ArrayUtils.remove(new Object[] {"a", "b"}, -1);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove(new Object[] {"a", "b"}, 2);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove((Object[]) null, 0);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new Object[] {"a", "b"}, -1));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new Object[] {"a", "b"}, 2));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((Object[]) null, 0));
}
@Test
@ -91,18 +82,9 @@ public class ArrayUtilsRemoveTest {
array = ArrayUtils.remove(new boolean[] {true, false, true}, 1);
assertTrue(Arrays.equals(new boolean[] {true, true}, array));
assertEquals(Boolean.TYPE, array.getClass().getComponentType());
try {
ArrayUtils.remove(new boolean[] {true, false}, -1);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove(new boolean[] {true, false}, 2);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove((boolean[]) null, 0);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new boolean[] {true, false}, -1));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new boolean[] {true, false}, 2));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((boolean[]) null, 0));
}
@Test
@ -120,18 +102,9 @@ public class ArrayUtilsRemoveTest {
array = ArrayUtils.remove(new byte[] {1, 2, 1}, 1);
assertTrue(Arrays.equals(new byte[] {1, 1}, array));
assertEquals(Byte.TYPE, array.getClass().getComponentType());
try {
ArrayUtils.remove(new byte[] {1, 2}, -1);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove(new byte[] {1, 2}, 2);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove((byte[]) null, 0);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new byte[] {1, 2}, -1));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new byte[] {1, 2}, 2));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((byte[]) null, 0));
}
@Test
@ -149,18 +122,9 @@ public class ArrayUtilsRemoveTest {
array = ArrayUtils.remove(new char[] {'a', 'b', 'c'}, 1);
assertTrue(Arrays.equals(new char[] {'a', 'c'}, array));
assertEquals(Character.TYPE, array.getClass().getComponentType());
try {
ArrayUtils.remove(new char[] {'a', 'b'}, -1);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove(new char[] {'a', 'b'}, 2);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove((char[]) null, 0);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new char[] {'a', 'b'}, -1));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new char[] {'a', 'b'}, 2));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((char[]) null, 0));
}
@Test
@ -178,18 +142,9 @@ public class ArrayUtilsRemoveTest {
array = ArrayUtils.remove(new double[] {1, 2, 1}, 1);
assertTrue(Arrays.equals(new double[] {1, 1}, array));
assertEquals(Double.TYPE, array.getClass().getComponentType());
try {
ArrayUtils.remove(new double[] {1, 2}, -1);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove(new double[] {1, 2}, 2);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove((double[]) null, 0);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new double[] {1, 2}, -1));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new double[] {1, 2}, 2));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((double[]) null, 0));
}
@Test
@ -207,18 +162,9 @@ public class ArrayUtilsRemoveTest {
array = ArrayUtils.remove(new float[] {1, 2, 1}, 1);
assertTrue(Arrays.equals(new float[] {1, 1}, array));
assertEquals(Float.TYPE, array.getClass().getComponentType());
try {
ArrayUtils.remove(new float[] {1, 2}, -1);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove(new float[] {1, 2}, 2);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove((float[]) null, 0);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new float[] {1, 2}, -1));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new float[] {1, 2}, 2));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((float[]) null, 0));
}
@Test
@ -236,18 +182,9 @@ public class ArrayUtilsRemoveTest {
array = ArrayUtils.remove(new int[] {1, 2, 1}, 1);
assertTrue(Arrays.equals(new int[] {1, 1}, array));
assertEquals(Integer.TYPE, array.getClass().getComponentType());
try {
ArrayUtils.remove(new int[] {1, 2}, -1);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove(new int[] {1, 2}, 2);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove((int[]) null, 0);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new int[] {1, 2}, -1));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new int[] {1, 2}, 2));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((int[]) null, 0));
}
@Test
@ -265,18 +202,9 @@ public class ArrayUtilsRemoveTest {
array = ArrayUtils.remove(new long[] {1, 2, 1}, 1);
assertTrue(Arrays.equals(new long[] {1, 1}, array));
assertEquals(Long.TYPE, array.getClass().getComponentType());
try {
ArrayUtils.remove(new long[] {1, 2}, -1);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove(new long[] {1, 2}, 2);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove((long[]) null, 0);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new long[] {1, 2}, -1));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new long[] {1, 2}, 2));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((long[]) null, 0));
}
@Test
@ -294,18 +222,9 @@ public class ArrayUtilsRemoveTest {
array = ArrayUtils.remove(new short[] {1, 2, 1}, 1);
assertTrue(Arrays.equals(new short[] {1, 1}, array));
assertEquals(Short.TYPE, array.getClass().getComponentType());
try {
ArrayUtils.remove(new short[] {1, 2}, -1);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove(new short[] {1, 2}, 2);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
try {
ArrayUtils.remove((short[]) null, 0);
fail("IndexOutOfBoundsException expected");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new short[] {1, 2}, -1));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove(new short[] {1, 2}, 2));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.remove((short[]) null, 0));
}
@Test

View File

@ -25,7 +25,6 @@ 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.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
@ -230,21 +229,12 @@ public class ArrayUtilsTest {
assertEquals("world", map.get("hello"));
assertNull(ArrayUtils.toMap(null));
try {
ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"short"}});
fail("exception expected");
} catch (final IllegalArgumentException ex) {
}
try {
ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, "illegal type"});
fail("exception expected");
} catch (final IllegalArgumentException ex) {
}
try {
ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, null});
fail("exception expected");
} catch (final IllegalArgumentException ex) {
}
assertThrows(IllegalArgumentException.class, () ->
ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"short"}}));
assertThrows(IllegalArgumentException.class, () ->
ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, "illegal type"}));
assertThrows(IllegalArgumentException.class, () ->
ArrayUtils.toMap(new Object[]{new Object[]{"foo", "bar"}, null}));
map = ArrayUtils.toMap(new Object[]{new Map.Entry<Object, Object>() {
@Override
@ -795,11 +785,9 @@ public class ArrayUtilsTest {
"java.util.Date type");
assertNotSame(java.sql.Date.class, ArrayUtils.subarray(dateArray, 1, 4).getClass().getComponentType(),
"java.sql.Date type");
try {
@SuppressWarnings("unused") final java.sql.Date[] dummy = (java.sql.Date[]) ArrayUtils.subarray(dateArray, 1, 3);
fail("Invalid downcast");
} catch (final ClassCastException e) {
}
assertThrows(ClassCastException.class,
() -> java.sql.Date[].class.cast(ArrayUtils.subarray(dateArray, 1, 3)),
"Invalid downcast");
}
@Test
@ -1406,21 +1394,9 @@ public class ArrayUtilsTest {
//-----------------------------------------------------------------------
@Test
public void testSameType() {
try {
ArrayUtils.isSameType(null, null);
fail();
} catch (final IllegalArgumentException ex) {
}
try {
ArrayUtils.isSameType(null, new Object[0]);
fail();
} catch (final IllegalArgumentException ex) {
}
try {
ArrayUtils.isSameType(new Object[0], null);
fail();
} catch (final IllegalArgumentException ex) {
}
assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSameType(null, null));
assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSameType(null, new Object[0]));
assertThrows(IllegalArgumentException.class, () -> ArrayUtils.isSameType(new Object[0], null));
assertTrue(ArrayUtils.isSameType(new Object[0], new Object[0]));
assertFalse(ArrayUtils.isSameType(new String[0], new Object[0]));
@ -3901,11 +3877,7 @@ public class ArrayUtilsTest {
ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, Boolean.FALSE, Boolean.TRUE}))
);
try {
ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, null});
fail();
} catch (final NullPointerException ex) {
}
assertThrows(NullPointerException.class, () -> ArrayUtils.toPrimitive(new Boolean[]{Boolean.TRUE, null}));
}
@Test
@ -3952,11 +3924,8 @@ public class ArrayUtilsTest {
new Character(Character.MAX_VALUE), new Character('0')}))
);
try {
ArrayUtils.toPrimitive(new Character[]{new Character(Character.MIN_VALUE), null});
fail();
} catch (final NullPointerException ex) {
}
assertThrows(NullPointerException.class,
() -> ArrayUtils.toPrimitive(new Character[]{new Character(Character.MIN_VALUE), null}));
}
@Test
@ -4012,11 +3981,8 @@ public class ArrayUtilsTest {
Byte.valueOf(Byte.MAX_VALUE), Byte.valueOf((byte) 9999999)}))
);
try {
ArrayUtils.toPrimitive(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), null});
fail();
} catch (final NullPointerException ex) {
}
assertThrows(NullPointerException.class,
() -> ArrayUtils.toPrimitive(new Byte[]{Byte.valueOf(Byte.MIN_VALUE), null}));
}
@Test
@ -4072,11 +4038,8 @@ public class ArrayUtilsTest {
Short.valueOf(Short.MAX_VALUE), Short.valueOf((short) 9999999)}))
);
try {
ArrayUtils.toPrimitive(new Short[]{Short.valueOf(Short.MIN_VALUE), null});
fail();
} catch (final NullPointerException ex) {
}
assertThrows(NullPointerException.class,
() -> ArrayUtils.toPrimitive(new Short[]{Short.valueOf(Short.MIN_VALUE), null}));
}
@Test
@ -4129,11 +4092,8 @@ public class ArrayUtilsTest {
Integer.valueOf(Integer.MAX_VALUE), Integer.valueOf(9999999)}))
);
try {
ArrayUtils.toPrimitive(new Integer[]{Integer.valueOf(Integer.MIN_VALUE), null});
fail();
} catch (final NullPointerException ex) {
}
assertThrows(NullPointerException.class,
() -> ArrayUtils.toPrimitive(new Integer[]{Integer.valueOf(Integer.MIN_VALUE), null}));
}
@Test
@ -4194,11 +4154,8 @@ public class ArrayUtilsTest {
Long.valueOf(Long.MAX_VALUE), Long.valueOf(9999999)}))
);
try {
ArrayUtils.toPrimitive(new Long[]{Long.valueOf(Long.MIN_VALUE), null});
fail();
} catch (final NullPointerException ex) {
}
assertThrows(NullPointerException.class,
() -> ArrayUtils.toPrimitive(new Long[]{Long.valueOf(Long.MIN_VALUE), null}));
}
@Test
@ -4256,11 +4213,8 @@ public class ArrayUtilsTest {
Float.valueOf(Float.MAX_VALUE), Float.valueOf(9999999)}))
);
try {
ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), null});
fail();
} catch (final NullPointerException ex) {
}
assertThrows(NullPointerException.class,
() -> ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), null}));
}
@Test
@ -4318,11 +4272,8 @@ public class ArrayUtilsTest {
Double.valueOf(Double.MAX_VALUE), Double.valueOf(9999999)}))
);
try {
ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), null});
fail();
} catch (final NullPointerException ex) {
}
assertThrows(NullPointerException.class,
() -> ArrayUtils.toPrimitive(new Float[]{Float.valueOf(Float.MIN_VALUE), null}));
}
@Test
@ -4565,11 +4516,7 @@ public class ArrayUtilsTest {
assertEquals(0, ArrayUtils.getLength(emptyBooleanArray));
assertEquals(1, ArrayUtils.getLength(notEmptyBooleanArray));
try {
ArrayUtils.getLength("notAnArray");
fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException e) {
}
assertThrows(IllegalArgumentException.class, () -> ArrayUtils.getLength("notAnArray"));
}
@Test
@ -4753,11 +4700,7 @@ public class ArrayUtilsTest {
final Object[] array = new Object[]{1, 2, 3, "array", "test"};
assertArrayEquals(new String[]{"1", "2", "3", "array", "test"}, ArrayUtils.toStringArray(array));
try {
ArrayUtils.toStringArray(new Object[]{null});
fail("NullPointerException expected!");
} catch (final NullPointerException expected) {
}
assertThrows(NullPointerException.class, () -> ArrayUtils.toStringArray(new Object[]{null}));
}
@Test

View File

@ -23,7 +23,6 @@ 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 static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.Modifier;
import java.util.Iterator;
@ -311,13 +310,8 @@ public class CharRangeTest {
@Test
public void testContainsNullArg() {
final CharRange range = CharRange.is('a');
try {
@SuppressWarnings("unused")
final
boolean contains = range.contains(null);
} catch(final IllegalArgumentException e) {
assertEquals("The Range must not be null", e.getMessage());
}
IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> range.contains(null));
assertEquals("The Range must not be null", e.getMessage());
}
@Test
@ -355,36 +349,21 @@ public class CharRangeTest {
final Iterator<Character> emptySetIt = emptySet.iterator();
assertNotNull(emptySetIt);
assertFalse(emptySetIt.hasNext());
try {
emptySetIt.next();
fail("Should throw NoSuchElementException");
} catch (final NoSuchElementException e) {
assertTrue(true);
}
assertThrows(NoSuchElementException.class, emptySetIt::next);
final Iterator<Character> notFirstIt = notFirst.iterator();
assertNotNull(notFirstIt);
assertTrue(notFirstIt.hasNext());
assertEquals(Character.valueOf((char) 0), notFirstIt.next());
assertFalse(notFirstIt.hasNext());
try {
notFirstIt.next();
fail("Should throw NoSuchElementException");
} catch (final NoSuchElementException e) {
assertTrue(true);
}
assertThrows(NoSuchElementException.class, notFirstIt::next);
final Iterator<Character> notLastIt = notLast.iterator();
assertNotNull(notLastIt);
assertTrue(notLastIt.hasNext());
assertEquals(Character.valueOf(Character.MAX_VALUE), notLastIt.next());
assertFalse(notLastIt.hasNext());
try {
notLastIt.next();
fail("Should throw NoSuchElementException");
} catch (final NoSuchElementException e) {
assertTrue(true);
}
assertThrows(NoSuchElementException.class, notLastIt::next);
}
//-----------------------------------------------------------------------

View File

@ -23,7 +23,6 @@ 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 static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
@ -83,7 +82,7 @@ public class CharSequenceUtilsTest {
final int ooffset;
final int len;
final boolean expected;
final Class<?> throwable;
final Class<? extends Throwable> throwable;
TestData(final String source, final boolean ignoreCase, final int toffset,
final String other, final int ooffset, final int len, final boolean expected){
this.source = source;
@ -96,7 +95,7 @@ public class CharSequenceUtilsTest {
this.throwable = null;
}
TestData(final String source, final boolean ignoreCase, final int toffset,
final String other, final int ooffset, final int len, final Class<?> throwable){
final String other, final int ooffset, final int len, final Class<? extends Throwable> throwable){
this.source = source;
this.ignoreCase = ignoreCase;
this.toffset = toffset;
@ -145,14 +144,7 @@ public class CharSequenceUtilsTest {
void run(final TestData data, final String id) {
if (data.throwable != null) {
try {
invoke();
fail(id + " Expected " + data.throwable);
} catch (final Exception e) {
if (!e.getClass().equals(data.throwable)) {
fail(id + " Expected " + data.throwable + " got " + e.getClass());
}
}
assertThrows(data.throwable, this::invoke, id + " Expected " + data.throwable);
} else {
final boolean stringCheck = invoke();
assertEquals(data.expected, stringCheck, id + " Failed test " + data);

View File

@ -21,8 +21,8 @@ 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 static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
@ -199,10 +199,7 @@ public class CharUtilsTest {
public void testToChar_Character() {
assertEquals('A', CharUtils.toChar(CHARACTER_A));
assertEquals('B', CharUtils.toChar(CHARACTER_B));
try {
CharUtils.toChar((Character) null);
fail("An IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {}
assertThrows(IllegalArgumentException.class, () -> CharUtils.toChar((Character) null));
}
@Test
@ -216,14 +213,8 @@ public class CharUtilsTest {
public void testToChar_String() {
assertEquals('A', CharUtils.toChar("A"));
assertEquals('B', CharUtils.toChar("BA"));
try {
CharUtils.toChar((String) null);
fail("An IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {}
try {
CharUtils.toChar("");
fail("An IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {}
assertThrows(IllegalArgumentException.class, () -> CharUtils.toChar((String) null));
assertThrows(IllegalArgumentException.class, () -> CharUtils.toChar(""));
}
@Test
@ -278,10 +269,7 @@ public class CharUtilsTest {
assertEquals(7, CharUtils.toIntValue('7'));
assertEquals(8, CharUtils.toIntValue('8'));
assertEquals(9, CharUtils.toIntValue('9'));
try {
CharUtils.toIntValue('a');
fail("An IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {}
assertThrows(IllegalArgumentException.class, () -> CharUtils.toIntValue('a'));
}
@Test
@ -295,14 +283,8 @@ public class CharUtilsTest {
public void testToIntValue_Character() {
assertEquals(0, CharUtils.toIntValue(new Character('0')));
assertEquals(3, CharUtils.toIntValue(new Character('3')));
try {
CharUtils.toIntValue(null);
fail("An IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {}
try {
CharUtils.toIntValue(CHARACTER_A);
fail("An IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {}
assertThrows(IllegalArgumentException.class, () -> CharUtils.toIntValue(null));
assertThrows(IllegalArgumentException.class, () -> CharUtils.toIntValue(CHARACTER_A));
}
@Test

View File

@ -25,7 +25,6 @@ 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.lang.reflect.Constructor;
import java.lang.reflect.Method;
@ -97,13 +96,10 @@ public class ClassUtilsTest {
assertGetClassThrowsException( className, ClassNotFoundException.class );
}
private void assertGetClassThrowsException( final String className, final Class<?> exceptionType ) throws Exception {
try {
ClassUtils.getClass( className );
fail( "ClassUtils.getClass() should fail with an exception of type " + exceptionType.getName() + " when given class name \"" + className + "\"." );
} catch( final Exception e ) {
assertTrue( exceptionType.isAssignableFrom( e.getClass() ) );
}
private void assertGetClassThrowsException(final String className, final Class<? extends Exception> exceptionType) {
assertThrows(exceptionType,
() -> ClassUtils.getClass(className),
"ClassUtils.getClass() should fail with an exception of type " + exceptionType.getName() + " when given class name \"" + className + "\"." );
}
private void assertGetClassThrowsNullPointerException( final String className ) throws Exception {
@ -128,12 +124,9 @@ public class ClassUtilsTest {
@SuppressWarnings("unchecked") // test what happens when non-generic code adds wrong type of element
final List<Object> olist = (List<Object>) (List<?>) list;
olist.add(new Object());
try {
ClassUtils.convertClassesToClassNames(list);
fail("Should not have been able to convert list");
} catch (final ClassCastException expected) {
// empty
}
assertThrows(ClassCastException.class,
() -> ClassUtils.convertClassesToClassNames(list),
"Should not have been able to convert list");
assertNull(ClassUtils.convertClassesToClassNames(null));
}
@ -156,12 +149,9 @@ public class ClassUtilsTest {
@SuppressWarnings("unchecked") // test what happens when non-generic code adds wrong type of element
final List<Object> olist = (List<Object>) (List<?>) list;
olist.add(new Object());
try {
ClassUtils.convertClassNamesToClasses(list);
fail("Should not have been able to convert list");
} catch (final ClassCastException expected) {
// empty
}
assertThrows(ClassCastException.class,
() -> ClassUtils.convertClassNamesToClasses(list),
"Should not have been able to convert list");
assertNull(ClassUtils.convertClassNamesToClasses(null));
}
@ -1208,17 +1198,12 @@ public class ClassUtilsTest {
// Tests with Collections$UnmodifiableSet
final Set<?> set = Collections.unmodifiableSet(new HashSet<>());
final Method isEmptyMethod = ClassUtils.getPublicMethod(set.getClass(), "isEmpty");
assertTrue(Modifier.isPublic(isEmptyMethod.getDeclaringClass().getModifiers()));
try {
isEmptyMethod.invoke(set);
} catch(final java.lang.IllegalAccessException iae) {
fail("Should not have thrown IllegalAccessException");
}
assertTrue(Modifier.isPublic(isEmptyMethod.getDeclaringClass().getModifiers()));
assertTrue((Boolean) isEmptyMethod.invoke(set));
// Tests with a public Class
final Method toStringMethod = ClassUtils.getPublicMethod(Object.class, "toString");
assertEquals(Object.class.getMethod("toString", new Class[0]), toStringMethod);
assertEquals(Object.class.getMethod("toString", new Class[0]), toStringMethod);
}
@Test
@ -1370,12 +1355,7 @@ public class ClassUtilsTest {
// Tests with Collections$UnmodifiableSet
final Set<?> set = Collections.unmodifiableSet(new HashSet<>());
final Method isEmptyMethod = set.getClass().getMethod("isEmpty");
try {
isEmptyMethod.invoke(set);
fail("Failed to throw IllegalAccessException as expected");
} catch(final IllegalAccessException iae) {
// expected
}
assertThrows(IllegalAccessException.class, () -> isEmptyMethod.invoke(set));
}
@Test

View File

@ -18,7 +18,7 @@ package org.apache.commons.lang3;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.UUID;
@ -57,12 +57,7 @@ public class ConversionTest {
assertEquals(14, Conversion.hexDigitToInt('e'));
assertEquals(15, Conversion.hexDigitToInt('F'));
assertEquals(15, Conversion.hexDigitToInt('f'));
try {
Conversion.hexDigitToInt('G');
fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
} catch (final IllegalArgumentException e) {
// OK
}
assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitToInt('G'));
}
/**
@ -92,12 +87,7 @@ public class ConversionTest {
assertEquals(0x7, Conversion.hexDigitMsb0ToInt('e'));
assertEquals(0xF, Conversion.hexDigitMsb0ToInt('F'));
assertEquals(0xF, Conversion.hexDigitMsb0ToInt('f'));
try {
Conversion.hexDigitMsb0ToInt('G');
fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
} catch (final IllegalArgumentException e) {
// OK
}
assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitMsb0ToInt('G'));
}
/**
@ -149,12 +139,7 @@ public class ConversionTest {
new boolean[]{true, true, true, true}, Conversion.hexDigitToBinary('F'));
assertArrayEquals(
new boolean[]{true, true, true, true}, Conversion.hexDigitToBinary('f'));
try {
Conversion.hexDigitToBinary('G');
fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
} catch (final IllegalArgumentException e) {
// OK
}
assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitToBinary('G'));
}
/**
@ -206,12 +191,7 @@ public class ConversionTest {
new boolean[]{true, true, true, true}, Conversion.hexDigitMsb0ToBinary('F'));
assertArrayEquals(
new boolean[]{true, true, true, true}, Conversion.hexDigitMsb0ToBinary('f'));
try {
Conversion.hexDigitMsb0ToBinary('G');
fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
} catch (final IllegalArgumentException e) {
// OK
}
assertThrows(IllegalArgumentException.class, () -> Conversion.hexDigitMsb0ToBinary('G'));
}
/**
@ -239,12 +219,7 @@ public class ConversionTest {
assertEquals('1', Conversion.binaryToHexDigit(new boolean[]{true}));
assertEquals(
'f', Conversion.binaryToHexDigit(new boolean[]{true, true, true, true, true}));
try {
Conversion.binaryToHexDigit(new boolean[]{});
fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
} catch (final IllegalArgumentException e) {
// OK
}
assertThrows(IllegalArgumentException.class, () -> Conversion.binaryToHexDigit(new boolean[]{}));
}
/**
@ -308,12 +283,7 @@ public class ConversionTest {
'e', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, true, false}));
assertEquals(
'f', Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{true, true, true, true}));
try {
Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{});
fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
} catch (final IllegalArgumentException e) {
// OK
}
assertThrows(IllegalArgumentException.class, () -> Conversion.binaryToHexDigitMsb0_4bits(new boolean[]{}));
}
/**
@ -393,12 +363,7 @@ public class ConversionTest {
Conversion.binaryBeMsb0ToHexDigit(new boolean[]{
true, false, false, false, false, false, false, false, false, false, false,
false, false, true, false, false}));
try {
Conversion.binaryBeMsb0ToHexDigit(new boolean[]{});
fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
} catch (final IllegalArgumentException e) {
// OK
}
assertThrows(IllegalArgumentException.class, () -> Conversion.binaryBeMsb0ToHexDigit(new boolean[]{}));
}
/**
@ -469,12 +434,7 @@ public class ConversionTest {
assertEquals('d', Conversion.intToHexDigit(13));
assertEquals('e', Conversion.intToHexDigit(14));
assertEquals('f', Conversion.intToHexDigit(15));
try {
Conversion.intToHexDigit(16);
fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
} catch (final IllegalArgumentException e) {
// OK
}
assertThrows(IllegalArgumentException.class, () -> Conversion.intToHexDigit(16));
}
/**
@ -498,12 +458,7 @@ public class ConversionTest {
assertEquals('b', Conversion.intToHexDigitMsb0(13));
assertEquals('7', Conversion.intToHexDigitMsb0(14));
assertEquals('f', Conversion.intToHexDigitMsb0(15));
try {
Conversion.intToHexDigitMsb0(16);
fail("Thrown " + IllegalArgumentException.class.getName() + " expected");
} catch (final IllegalArgumentException e) {
// OK
}
assertThrows(IllegalArgumentException.class, () -> Conversion.intToHexDigitMsb0(16));
}
static String dbgPrint(final boolean[] src) {
@ -1276,12 +1231,7 @@ public class ConversionTest {
Conversion.longToHex(0x1234567890ABCDEFL, 4, "ffffffffffffffffffffffff", 3, 15));
assertEquals(
"fedcba0987654321", Conversion.longToHex(0x1234567890ABCDEFL, 0, "", 0, 16));
try {
Conversion.longToHex(0x1234567890ABCDEFL, 0, "", 1, 8);
fail("Thrown " + StringIndexOutOfBoundsException.class.getName() + " expected");
} catch (final StringIndexOutOfBoundsException e) {
// OK
}
assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.longToHex(0x1234567890ABCDEFL, 0, "", 1, 8));
}
/**
@ -1340,12 +1290,7 @@ public class ConversionTest {
"fffedcba09ffffffffffffff",
Conversion.intToHex(0x90ABCDEF, 4, "ffffffffffffffffffffffff", 3, 7));
assertEquals("fedcba09", Conversion.intToHex(0x90ABCDEF, 0, "", 0, 8));
try {
Conversion.intToHex(0x90ABCDEF, 0, "", 1, 8);
fail("Thrown " + StringIndexOutOfBoundsException.class.getName() + " expected");
} catch (final StringIndexOutOfBoundsException e) {
// OK
}
assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.intToHex(0x90ABCDEF, 0, "", 1, 8));
}
/**
@ -1392,12 +1337,7 @@ public class ConversionTest {
"fffedcffffffffffffffffff",
Conversion.shortToHex((short)0xCDEF, 4, "ffffffffffffffffffffffff", 3, 3));
assertEquals("fedc", Conversion.shortToHex((short)0xCDEF, 0, "", 0, 4));
try {
Conversion.shortToHex((short)0xCDEF, 0, "", 1, 4);
fail("Thrown " + StringIndexOutOfBoundsException.class.getName() + " expected");
} catch (final StringIndexOutOfBoundsException e) {
// OK
}
assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.shortToHex((short)0xCDEF, 0, "", 1, 4));
}
/**
@ -1420,12 +1360,7 @@ public class ConversionTest {
// assertion
assertEquals("000e0", Conversion.byteToHex((byte)0xEF, 4, "00000", 3, 1));
assertEquals("fe", Conversion.byteToHex((byte)0xEF, 0, "", 0, 2));
try {
Conversion.byteToHex((byte)0xEF, 0, "", 1, 2);
fail("Thrown " + StringIndexOutOfBoundsException.class.getName() + " expected");
} catch (final StringIndexOutOfBoundsException e) {
// OK
}
assertThrows(StringIndexOutOfBoundsException.class, () -> Conversion.byteToHex((byte)0xEF, 0, "", 1, 2));
}
/**

View File

@ -22,6 +22,7 @@ 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 static org.junit.jupiter.api.Assertions.fail;
@ -138,32 +139,13 @@ public class LocaleUtilsTest {
// LANG-941: JDK 8 introduced the empty locale as one of the default locales
assertValidToLocale("");
try {
LocaleUtils.toLocale("Us");
fail("Should fail if not lowercase");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("US");
fail("Should fail if not lowercase");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uS");
fail("Should fail if not lowercase");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("u#");
fail("Should fail if not lowercase");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("u");
fail("Must be 2 chars if less than 5");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uu_U");
fail("Must be 2 chars if less than 5");
} catch (final IllegalArgumentException iae) {}
assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale("Us"), "Should fail if not lowercase");
assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale("uS"), "Should fail if not lowercase");
assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale("u#"), "Should fail if not lowercase");
assertThrows(
IllegalArgumentException.class, () -> LocaleUtils.toLocale("u"), "Must be 2 chars if less than 5");
assertThrows(
IllegalArgumentException.class, () -> LocaleUtils.toLocale("uu_U"), "Must be 2 chars if less than 5");
}
/**
@ -175,30 +157,28 @@ public class LocaleUtilsTest {
//valid though doesn't exist
assertValidToLocale("us_ZH", "us", "ZH");
try {
LocaleUtils.toLocale("us-EN");
fail("Should fail as not underscore");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_En");
fail("Should fail second part not uppercase");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_en");
fail("Should fail second part not uppercase");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_eN");
fail("Should fail second part not uppercase");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uS_EN");
fail("Should fail first part not lowercase");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("us_E3");
fail("Should fail second part not uppercase");
} catch (final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class, () -> LocaleUtils.toLocale("us-EN"), "Should fail as not underscore");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("us_En"),
"Should fail second part not uppercase");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("us_en"),
"Should fail second part not uppercase");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("us_eN"),
"Should fail second part not uppercase");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("uS_EN"),
"Should fail first part not lowercase");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("us_E3"),
"Should fail second part not uppercase");
}
/**
@ -217,14 +197,10 @@ public class LocaleUtilsTest {
assertValidToLocale("us_EN_SFsafdFDsdfF", "us", "EN", "SFSAFDFDSDFF");
}
try {
LocaleUtils.toLocale("us_EN-a");
fail("Should fail as not underscore");
} catch (final IllegalArgumentException iae) {}
try {
LocaleUtils.toLocale("uu_UU_");
fail("Must be 3, 5 or 7+ in length");
} catch (final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class, () -> LocaleUtils.toLocale("us_EN-a"), "Should fail as not underscore");
assertThrows(
IllegalArgumentException.class, () -> LocaleUtils.toLocale("uu_UU_"), "Must be 3, 5 or 7+ in length");
}
//-----------------------------------------------------------------------
@ -492,10 +468,7 @@ public class LocaleUtilsTest {
* @param coll the collection to check
*/
private static void assertUnmodifiableCollection(final Collection<?> coll) {
try {
coll.add(null);
fail();
} catch (final UnsupportedOperationException ex) {}
assertThrows(UnsupportedOperationException.class, () -> coll.add(null));
}
/**
@ -526,41 +499,34 @@ public class LocaleUtilsTest {
assertValidToLocale("_GB", "", "GB", "");
assertValidToLocale("_GB_P", "", "GB", "P");
assertValidToLocale("_GB_POSIX", "", "GB", "POSIX");
try {
LocaleUtils.toLocale("_G");
fail("Must be at least 3 chars if starts with underscore");
} catch (final IllegalArgumentException iae) {
}
try {
LocaleUtils.toLocale("_Gb");
fail("Must be uppercase if starts with underscore");
} catch (final IllegalArgumentException iae) {
}
try {
LocaleUtils.toLocale("_gB");
fail("Must be uppercase if starts with underscore");
} catch (final IllegalArgumentException iae) {
}
try {
LocaleUtils.toLocale("_1B");
fail("Must be letter if starts with underscore");
} catch (final IllegalArgumentException iae) {
}
try {
LocaleUtils.toLocale("_G1");
fail("Must be letter if starts with underscore");
} catch (final IllegalArgumentException iae) {
}
try {
LocaleUtils.toLocale("_GB_");
fail("Must be at least 5 chars if starts with underscore");
} catch (final IllegalArgumentException iae) {
}
try {
LocaleUtils.toLocale("_GBAP");
fail("Must have underscore after the country if starts with underscore and is at least 5 chars");
} catch (final IllegalArgumentException iae) {
}
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("_G"),
"Must be at least 3 chars if starts with underscore");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("_Gb"),
"Must be uppercase if starts with underscore");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("_gB"),
"Must be uppercase if starts with underscore");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("_1B"),
"Must be letter if starts with underscore");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("_G1"),
"Must be letter if starts with underscore");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("_GB_"),
"Must be at least 5 chars if starts with underscore");
assertThrows(
IllegalArgumentException.class,
() -> LocaleUtils.toLocale("_GBAP"),
"Must have underscore after the country if starts with underscore and is at least 5 chars");
}
@ParameterizedTest
@ -569,22 +535,19 @@ public class LocaleUtilsTest {
// Check if it's possible to recreate the Locale using just the standard constructor
final Locale locale = new Locale(l.getLanguage(), l.getCountry(), l.getVariant());
if (l.equals(locale)) { // it is possible for LocaleUtils.toLocale to handle these Locales
String str = l.toString();
final String str = l.toString();
// Look for the script/extension suffix
int suff = str.indexOf("_#");
if (suff == - 1) {
suff = str.indexOf("#");
}
String localeStr = str;
if (suff >= 0) { // we have a suffix
try {
LocaleUtils.toLocale(str); // should cause IAE
fail("Should not have parsed: " + str);
} catch (final IllegalArgumentException iae) {
// expected; try without suffix
str = str.substring(0, suff);
}
assertThrows(IllegalArgumentException.class, () -> LocaleUtils.toLocale(str));
// try without suffix
localeStr = str.substring(0, suff);
}
final Locale loc = LocaleUtils.toLocale(str);
final Locale loc = LocaleUtils.toLocale(localeStr);
assertEquals(l, loc);
}
}

View File

@ -24,7 +24,6 @@ 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.io.IOException;
import java.lang.reflect.Constructor;
@ -227,16 +226,8 @@ public class ObjectUtilsTest {
ObjectUtils.identityToString(buffer, i);
assertEquals(expected, buffer.toString());
try {
ObjectUtils.identityToString((StringBuffer)null, "tmp");
fail("NullPointerException expected");
} catch(final NullPointerException npe) {
}
try {
ObjectUtils.identityToString(new StringBuffer(), null);
fail("NullPointerException expected");
} catch(final NullPointerException npe) {
}
assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((StringBuffer)null, "tmp"));
assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString(new StringBuffer(), null));
}
@Test
@ -281,20 +272,12 @@ public class ObjectUtilsTest {
@Test
public void testIdentityToStringStringBuilderNullValue() {
try {
ObjectUtils.identityToString(new StringBuilder(), null);
fail("NullPointerException expected");
} catch(final NullPointerException npe) {
}
assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString(new StringBuilder(), null));
}
@Test
public void testIdentityToStringStringBuilderNullStringBuilder() {
try {
ObjectUtils.identityToString((StringBuilder)null, "tmp");
fail("NullPointerException expected");
} catch(final NullPointerException npe) {
}
assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((StringBuilder)null, "tmp"));
}
@Test
@ -306,47 +289,25 @@ public class ObjectUtilsTest {
ObjectUtils.identityToString(builder, i);
assertEquals(expected, builder.toString());
try {
ObjectUtils.identityToString((StrBuilder)null, "tmp");
fail("NullPointerException expected");
} catch(final NullPointerException npe) {
}
assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((StrBuilder)null, "tmp"));
try {
ObjectUtils.identityToString(new StrBuilder(), null);
fail("NullPointerException expected");
} catch(final NullPointerException npe) {
}
assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString(new StrBuilder(), null));
}
@Test
public void testIdentityToStringAppendable() {
public void testIdentityToStringAppendable() throws IOException {
final Integer i = Integer.valueOf(121);
final String expected = "java.lang.Integer@" + Integer.toHexString(System.identityHashCode(i));
try {
final Appendable appendable = new StringBuilder();
ObjectUtils.identityToString(appendable, i);
assertEquals(expected, appendable.toString());
} catch(final IOException ex) {
fail("IOException unexpected");
}
final Appendable appendable = new StringBuilder();
ObjectUtils.identityToString(appendable, i);
assertEquals(expected, appendable.toString());
try {
ObjectUtils.identityToString((Appendable)null, "tmp");
fail("NullPointerException expected");
} catch(final NullPointerException expectedException) {
} catch(final IOException ex) {
fail("IOException unexpected");
}
assertThrows(NullPointerException.class, () -> ObjectUtils.identityToString((Appendable)null, "tmp"));
try {
ObjectUtils.identityToString((Appendable)(new StringBuilder()), null);
fail("NullPointerException expected");
} catch(final NullPointerException expectedException) {
} catch(final IOException ex) {
fail("IOException unexpected");
}
assertThrows(
NullPointerException.class,
() -> ObjectUtils.identityToString((Appendable)(new StringBuilder()), null));
}
@Test
@ -641,32 +602,22 @@ public class ObjectUtilsTest {
assertTrue(1.0f == MAGIC_FLOAT);
assertTrue(1.0 == MAGIC_DOUBLE);
assertEquals("abc", MAGIC_STRING);
try {
ObjectUtils.CONST_BYTE(-129);
fail("CONST_BYTE(-129): IllegalArgumentException should have been thrown.");
} catch (final IllegalArgumentException iae) {
}
try {
ObjectUtils.CONST_BYTE(128);
fail("CONST_BYTE(128): IllegalArgumentException should have been thrown.");
} catch (final IllegalArgumentException iae) {
}
try {
ObjectUtils.CONST_SHORT(-32769);
fail("CONST_SHORT(-32769): IllegalArgumentException should have been thrown.");
} catch (final IllegalArgumentException iae) {
}
try {
ObjectUtils.CONST_BYTE(32768);
fail("CONST_SHORT(32768): IllegalArgumentException should have been thrown.");
} catch (final IllegalArgumentException iae) {
}
assertThrows(
IllegalArgumentException.class,
() -> ObjectUtils.CONST_BYTE(-129),
"CONST_BYTE(-129): IllegalArgumentException should have been thrown.");
assertThrows(
IllegalArgumentException.class,
() -> ObjectUtils.CONST_BYTE(128),
"CONST_BYTE(128): IllegalArgumentException should have been thrown.");
assertThrows(
IllegalArgumentException.class,
() -> ObjectUtils.CONST_SHORT(-32769),
"CONST_SHORT(-32769): IllegalArgumentException should have been thrown.");
assertThrows(
IllegalArgumentException.class,
() -> ObjectUtils.CONST_BYTE(32768),
"CONST_SHORT(32768): IllegalArgumentException should have been thrown.");
}
/**

View File

@ -24,6 +24,7 @@ import static org.hamcrest.Matchers.lessThanOrEqualTo;
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 static org.junit.jupiter.api.Assertions.fail;
@ -157,63 +158,29 @@ public class RandomStringUtilsTest {
@Test
public void testLANG807() {
try {
RandomStringUtils.random(3,5,5,false,false);
fail("Expected IllegalArgumentException");
} catch (final IllegalArgumentException ex) { // distinguish from Random#nextInt message
final String msg = ex.getMessage();
assertTrue(msg.contains("start"), "Message (" + msg + ") must contain 'start'");
assertTrue(msg.contains("end"), "Message (" + msg + ") must contain 'end'");
}
IllegalArgumentException ex =
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(3,5,5,false,false));
final String msg = ex.getMessage();
assertTrue(msg.contains("start"), "Message (" + msg + ") must contain 'start'");
assertTrue(msg.contains("end"), "Message (" + msg + ") must contain 'end'");
}
@Test
public void testExceptions() {
final char[] DUMMY = new char[]{'a'}; // valid char array
try {
RandomStringUtils.random(-1);
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(-1, true, true);
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(-1, DUMMY);
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(1, new char[0]); // must not provide empty array => IAE
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(-1, "");
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(-1, (String)null);
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(-1, 'a', 'z', false, false);
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY);
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random());
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(8, 32, 48, false, true);
fail();
} catch (final IllegalArgumentException ex) {}
try {
RandomStringUtils.random(8, 32, 65, true, false);
fail();
} catch (final IllegalArgumentException ex) {}
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, true, true));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, DUMMY));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(1, new char[0]));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, ""));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, (String) null));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, 'a', 'z', false, false));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY));
assertThrows(
IllegalArgumentException.class,
() -> RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random()));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(8, 32, 48, false, true));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(8, 32, 65, true, false));
}
/**

View File

@ -23,7 +23,6 @@ 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 static org.junit.jupiter.api.Assertions.fail;
import java.util.Comparator;
@ -254,12 +253,7 @@ public class RangeTest {
@Test
public void testElementCompareTo() {
try {
intRange.elementCompareTo(null);
fail("NullPointerException should have been thrown");
} catch (final NullPointerException npe) {
// expected
}
assertThrows(NullPointerException.class, () -> intRange.elementCompareTo(null));
assertEquals(-1, intRange.elementCompareTo(5));
assertEquals(0, intRange.elementCompareTo(10));

View File

@ -18,7 +18,7 @@ package org.apache.commons.lang3;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
@ -64,12 +64,10 @@ public class RegExUtilsTest {
assertEquals("AB", RegExUtils.removeAll("A<__>\n<__>B", "(?s)<.*>"));
assertEquals("ABC123", RegExUtils.removeAll("ABCabc123abc", "[a-z]"));
try {
RegExUtils.removeAll("any", "{badRegexSyntax}");
fail("RegExUtils.removeAll expecting PatternSyntaxException");
} catch (final PatternSyntaxException ex) {
// empty
}
assertThrows(
PatternSyntaxException.class,
() -> RegExUtils.removeAll("any", "{badRegexSyntax}"),
"RegExUtils.removeAll expecting PatternSyntaxException");
}
@Test
@ -103,12 +101,10 @@ public class RegExUtilsTest {
assertEquals("ABCbc123", RegExUtils.removeFirst("ABCabc123", "[a-z]"));
assertEquals("ABC123abc", RegExUtils.removeFirst("ABCabc123abc", "[a-z]+"));
try {
RegExUtils.removeFirst("any", "{badRegexSyntax}");
fail("RegExUtils.removeFirst expecting PatternSyntaxException");
} catch (final PatternSyntaxException ex) {
// empty
}
assertThrows(
PatternSyntaxException.class,
() -> RegExUtils.removeFirst("any", "{badRegexSyntax}"),
"RegExUtils.removeFirst expecting PatternSyntaxException");
}
@Test
@ -174,12 +170,10 @@ public class RegExUtilsTest {
assertEquals("ABC123", RegExUtils.replaceAll("ABCabc123", "[^A-Z0-9]+", ""));
assertEquals("Lorem_ipsum_dolor_sit", RegExUtils.replaceAll("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2"));
try {
RegExUtils.replaceAll("any", "{badRegexSyntax}", "");
fail("RegExUtils.replaceAll expecting PatternSyntaxException");
} catch (final PatternSyntaxException ex) {
// empty
}
assertThrows(
PatternSyntaxException.class,
() -> RegExUtils.replaceAll("any", "{badRegexSyntax}", ""),
"RegExUtils.replaceAll expecting PatternSyntaxException");
}
@Test
@ -225,12 +219,10 @@ public class RegExUtilsTest {
assertEquals("Lorem_ipsum dolor sit",
RegExUtils.replaceFirst("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2"));
try {
RegExUtils.replaceFirst("any", "{badRegexSyntax}", "");
fail("RegExUtils.replaceFirst expecting PatternSyntaxException");
} catch (final PatternSyntaxException ex) {
// empty
}
assertThrows(
PatternSyntaxException.class,
() -> RegExUtils.replaceFirst("any", "{badRegexSyntax}", ""),
"RegExUtils.replaceFirst expecting PatternSyntaxException");
}
@Test

View File

@ -159,11 +159,9 @@ public class SerializationUtilsTest {
throw new IOException(SERIALIZE_IO_EXCEPTION_MESSAGE);
}
};
try {
SerializationUtils.serialize(iMap, streamTest);
} catch(final SerializationException e) {
assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage());
}
SerializationException e =
assertThrows(SerializationException.class, () -> SerializationUtils.serialize(iMap, streamTest));
assertEquals("java.io.IOException: " + SERIALIZE_IO_EXCEPTION_MESSAGE, e.getMessage());
}
//-----------------------------------------------------------------------
@ -234,13 +232,9 @@ public class SerializationUtilsTest {
oos.close();
final ByteArrayInputStream inTest = new ByteArrayInputStream(streamReal.toByteArray());
try {
@SuppressWarnings("unused")
final
Object test = SerializationUtils.deserialize(inTest);
} catch(final SerializationException se) {
assertEquals("java.lang.ClassNotFoundException: " + CLASS_NOT_FOUND_MESSAGE, se.getMessage());
}
SerializationException se =
assertThrows(SerializationException.class, () -> SerializationUtils.deserialize(inTest));
assertEquals("java.lang.ClassNotFoundException: " + CLASS_NOT_FOUND_MESSAGE, se.getMessage());
}
@Test

View File

@ -22,7 +22,6 @@ 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 static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.io.StringWriter;
@ -57,20 +56,8 @@ public class StringEscapeUtilsTest {
@Test
public void testEscapeJava() throws IOException {
assertNull(StringEscapeUtils.escapeJava(null));
try {
StringEscapeUtils.ESCAPE_JAVA.translate(null, null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.ESCAPE_JAVA.translate("", null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.ESCAPE_JAVA.translate(null, null));
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.ESCAPE_JAVA.translate("", null));
assertEscapeJava("empty string", "", "");
assertEscapeJava(FOO, FOO);
@ -126,25 +113,9 @@ public class StringEscapeUtilsTest {
@Test
public void testUnescapeJava() throws IOException {
assertNull(StringEscapeUtils.unescapeJava(null));
try {
StringEscapeUtils.UNESCAPE_JAVA.translate(null, null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.UNESCAPE_JAVA.translate("", null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.unescapeJava("\\u02-3");
fail();
} catch (final RuntimeException ex) {
}
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.UNESCAPE_JAVA.translate(null, null));
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.UNESCAPE_JAVA.translate("", null));
assertThrows(RuntimeException.class, () -> StringEscapeUtils.unescapeJava("\\u02-3"));
assertUnescapeJava("", "");
assertUnescapeJava("test", "test");
@ -182,20 +153,8 @@ public class StringEscapeUtilsTest {
@Test
public void testEscapeEcmaScript() {
assertNull(StringEscapeUtils.escapeEcmaScript(null));
try {
StringEscapeUtils.ESCAPE_ECMASCRIPT.translate(null, null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.ESCAPE_ECMASCRIPT.translate("", null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.ESCAPE_ECMASCRIPT.translate(null, null));
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.ESCAPE_ECMASCRIPT.translate("", null));
assertEquals("He didn\\'t say, \\\"stop!\\\"", StringEscapeUtils.escapeEcmaScript("He didn't say, \"stop!\""));
assertEquals("document.getElementById(\\\"test\\\").value = \\'<script>alert(\\'aaa\\');<\\/script>\\';",
@ -205,20 +164,8 @@ public class StringEscapeUtilsTest {
@Test
public void testUnescapeEcmaScript() {
assertNull(StringEscapeUtils.escapeEcmaScript(null));
try {
StringEscapeUtils.UNESCAPE_ECMASCRIPT.translate(null, null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.UNESCAPE_ECMASCRIPT.translate("", null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.UNESCAPE_ECMASCRIPT.translate(null, null));
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.UNESCAPE_ECMASCRIPT.translate("", null));
assertEquals("He didn't say, \"stop!\"", StringEscapeUtils.unescapeEcmaScript("He didn\\'t say, \\\"stop!\\\""));
assertEquals("document.getElementById(\"test\").value = '<script>alert('aaa');</script>';",
@ -244,24 +191,21 @@ public class StringEscapeUtilsTest {
};
@Test
public void testEscapeHtml() {
public void testEscapeHtml() throws IOException {
for (final String[] element : HTML_ESCAPES) {
final String message = element[0];
final String expected = element[1];
final String original = element[2];
assertEquals(expected, StringEscapeUtils.escapeHtml4(original), message);
final StringWriter sw = new StringWriter();
try {
StringEscapeUtils.ESCAPE_HTML4.translate(original, sw);
} catch (final IOException e) {
}
StringEscapeUtils.ESCAPE_HTML4.translate(original, sw);
final String actual = original == null ? null : sw.toString();
assertEquals(expected, actual, message);
}
}
@Test
public void testUnescapeHtml4() {
public void testUnescapeHtml4() throws IOException {
for (final String[] element : HTML_ESCAPES) {
final String message = element[0];
final String expected = element[2];
@ -269,10 +213,7 @@ public class StringEscapeUtilsTest {
assertEquals(expected, StringEscapeUtils.unescapeHtml4(original), message);
final StringWriter sw = new StringWriter();
try {
StringEscapeUtils.UNESCAPE_HTML4.translate(original, sw);
} catch (final IOException e) {
}
StringEscapeUtils.UNESCAPE_HTML4.translate(original, sw);
final String actual = original == null ? null : sw.toString();
assertEquals(expected, actual, message);
}
@ -337,17 +278,11 @@ public class StringEscapeUtilsTest {
assertNull(StringEscapeUtils.unescapeXml(null));
StringWriter sw = new StringWriter();
try {
StringEscapeUtils.ESCAPE_XML.translate("<abc>", sw);
} catch (final IOException e) {
}
StringEscapeUtils.ESCAPE_XML.translate("<abc>", sw);
assertEquals("&lt;abc&gt;", sw.toString(), "XML was escaped incorrectly");
sw = new StringWriter();
try {
StringEscapeUtils.UNESCAPE_XML.translate("&lt;abc&gt;", sw);
} catch (final IOException e) {
}
StringEscapeUtils.UNESCAPE_XML.translate("&lt;abc&gt;", sw);
assertEquals("<abc>", sw.toString(), "XML was unescaped incorrectly");
}
@ -481,14 +416,10 @@ public class StringEscapeUtilsTest {
checkCsvEscapeWriter("", "");
}
private void checkCsvEscapeWriter(final String expected, final String value) {
try {
final StringWriter writer = new StringWriter();
StringEscapeUtils.ESCAPE_CSV.translate(value, writer);
assertEquals(expected, writer.toString());
} catch (final IOException e) {
fail("Threw: " + e);
}
private void checkCsvEscapeWriter(final String expected, final String value) throws IOException {
final StringWriter writer = new StringWriter();
StringEscapeUtils.ESCAPE_CSV.translate(value, writer);
assertEquals(expected, writer.toString());
}
@Test
@ -525,14 +456,10 @@ public class StringEscapeUtilsTest {
checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\"");
}
private void checkCsvUnescapeWriter(final String expected, final String value) {
try {
final StringWriter writer = new StringWriter();
StringEscapeUtils.UNESCAPE_CSV.translate(value, writer);
assertEquals(expected, writer.toString());
} catch (final IOException e) {
fail("Threw: " + e);
}
private void checkCsvUnescapeWriter(final String expected, final String value) throws IOException {
final StringWriter writer = new StringWriter();
StringEscapeUtils.UNESCAPE_CSV.translate(value, writer);
assertEquals(expected, writer.toString());
}
@Test
@ -622,20 +549,8 @@ public class StringEscapeUtilsTest {
@Test
public void testEscapeJson() {
assertNull(StringEscapeUtils.escapeJson(null));
try {
StringEscapeUtils.ESCAPE_JSON.translate(null, null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.ESCAPE_JSON.translate("", null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.ESCAPE_JSON.translate(null, null));
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.ESCAPE_JSON.translate("", null));
assertEquals("He didn't say, \\\"stop!\\\"", StringEscapeUtils.escapeJson("He didn't say, \"stop!\""));
@ -648,20 +563,8 @@ public class StringEscapeUtilsTest {
@Test
public void testUnescapeJson() {
assertNull(StringEscapeUtils.unescapeJson(null));
try {
StringEscapeUtils.UNESCAPE_JSON.translate(null, null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
try {
StringEscapeUtils.UNESCAPE_JSON.translate("", null);
fail();
} catch (final IOException ex) {
fail();
} catch (final IllegalArgumentException ex) {
}
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.UNESCAPE_JSON.translate(null, null));
assertThrows(IllegalArgumentException.class, () -> StringEscapeUtils.UNESCAPE_JSON.translate("", null));
assertEquals("He didn't say, \"stop!\"", StringEscapeUtils.unescapeJson("He didn't say, \\\"stop!\\\""));

View File

@ -1273,12 +1273,10 @@ public class StringUtilsTest {
assertEquals("Lorem_ipsum_dolor_sit",
StringUtils.replaceAll("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2"));
try {
StringUtils.replaceAll("any", "{badRegexSyntax}", "");
fail("StringUtils.replaceAll expecting PatternSyntaxException");
} catch (final PatternSyntaxException ex) {
// empty
}
assertThrows(
PatternSyntaxException.class,
() -> StringUtils.replaceAll("any", "{badRegexSyntax}", ""),
"StringUtils.replaceAll expecting PatternSyntaxException");
}
@Test
@ -1302,12 +1300,10 @@ public class StringUtilsTest {
assertEquals("Lorem_ipsum dolor sit",
StringUtils.replaceFirst("Lorem ipsum dolor sit", "( +)([a-z]+)", "_$2"));
try {
StringUtils.replaceFirst("any", "{badRegexSyntax}", "");
fail("StringUtils.replaceFirst expecting PatternSyntaxException");
} catch (final PatternSyntaxException ex) {
// empty
}
assertThrows(
PatternSyntaxException.class,
() -> StringUtils.replaceFirst("any", "{badRegexSyntax}", ""),
"StringUtils.replaceFirst expecting PatternSyntaxException");
}
@Test
@ -1450,12 +1446,10 @@ public class StringUtilsTest {
assertEquals(StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{null}), "aba");
assertEquals(StringUtils.replaceEach("aba", new String[]{"a", "b"}, new String[]{"c", null}), "cbc");
try {
StringUtils.replaceEach("abba", new String[]{"a"}, new String[]{"b", "a"});
fail("StringUtils.replaceEach(String, String[], String[]) expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
// expected
}
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.replaceEach("abba", new String[]{"a"}, new String[]{"b", "a"}),
"StringUtils.replaceEach(String, String[], String[]) expecting IllegalArgumentException");
}
/**
@ -1476,11 +1470,10 @@ public class StringUtilsTest {
assertEquals(StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}), "wcte");
assertEquals(StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}), "tcte");
try {
StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"});
fail("Should be a circular reference");
} catch (final IllegalStateException e) {
}
assertThrows(
IllegalStateException.class,
() -> StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}),
"Should be a circular reference");
//JAVADOC TESTS END
}
@ -1981,12 +1974,10 @@ public class StringUtilsTest {
assertEquals("a...", StringUtils.abbreviate("abcdefg", 4));
assertEquals("", StringUtils.abbreviate("", 4));
try {
StringUtils.abbreviate("abc", 3);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
// empty
}
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.abbreviate("abc", 3),
"StringUtils.abbreviate expecting IllegalArgumentException");
}
@Test
@ -2008,14 +1999,10 @@ public class StringUtilsTest {
assertEquals("abc.", StringUtils.abbreviate("abcdefg", ".", 4));
assertEquals("", StringUtils.abbreviate("", 4));
try {
@SuppressWarnings("unused")
final
String res = StringUtils.abbreviate("abcdefghij", "...", 3);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {
// empty
}
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.abbreviate("abcdefghij", "...", 3),
"StringUtils.abbreviate expecting IllegalArgumentException");
}
@Test
@ -2024,19 +2011,14 @@ public class StringUtilsTest {
assertEquals("", StringUtils.abbreviate("", 0, 10));
assertEquals("", StringUtils.abbreviate("", 2, 10));
try {
StringUtils.abbreviate("abcdefghij", 0, 3);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
// empty
}
try {
StringUtils.abbreviate("abcdefghij", 5, 6);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
// empty
}
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.abbreviate("abcdefghij", 0, 3),
"StringUtils.abbreviate expecting IllegalArgumentException");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.abbreviate("abcdefghij", 5, 6),
"StringUtils.abbreviate expecting IllegalArgumentException");
final String raspberry = "raspberry peach";
assertEquals("raspberry peach", StringUtils.abbreviate(raspberry, 11, 15));
@ -2084,18 +2066,14 @@ public class StringUtilsTest {
assertEquals("", StringUtils.abbreviate("", null, 0, 10));
assertEquals("", StringUtils.abbreviate("", "...", 2, 10));
try {
StringUtils.abbreviate("abcdefghij", "::", 0, 2);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
// empty
}
try {
StringUtils.abbreviate("abcdefghij", "!!!", 5, 6);
fail("StringUtils.abbreviate expecting IllegalArgumentException");
} catch (final IllegalArgumentException expected) {
// empty
}
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.abbreviate("abcdefghij", "::", 0, 2),
"StringUtils.abbreviate expecting IllegalArgumentException");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.abbreviate("abcdefghij", "!!!", 5, 6),
"StringUtils.abbreviate expecting IllegalArgumentException");
final String raspberry = "raspberry peach";
assertEquals("raspberry peach", StringUtils.abbreviate(raspberry, "--", 12, 15));
@ -2181,47 +2159,31 @@ public class StringUtilsTest {
@Test
public void testTruncate_StringInt() {
assertNull(StringUtils.truncate(null, 12));
try {
StringUtils.truncate(null, -1);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate(null, -10);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate(null, Integer.MIN_VALUE);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
assertThrows(
IllegalArgumentException.class, () -> StringUtils.truncate(null, -1), "maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class, () -> StringUtils.truncate(null, -10), "maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate(null, Integer.MIN_VALUE),
"maxWith cannot be negative");
assertEquals("", StringUtils.truncate("", 10));
assertEquals("", StringUtils.truncate("", 10));
assertEquals("abc", StringUtils.truncate("abcdefghij", 3));
assertEquals("abcdef", StringUtils.truncate("abcdefghij", 6));
assertEquals("", StringUtils.truncate("abcdefghij", 0));
try {
StringUtils.truncate("abcdefghij", -1);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", -100);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", Integer.MIN_VALUE);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", -1),
"maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", -100),
"maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", Integer.MIN_VALUE),
"maxWith cannot be negative");
assertEquals("abcdefghij", StringUtils.truncate("abcdefghijklmno", 10));
assertEquals("abcdefghijklmno", StringUtils.truncate("abcdefghijklmno", Integer.MAX_VALUE));
assertEquals("abcde", StringUtils.truncate("abcdefghijklmno", 5));
@ -2231,108 +2193,74 @@ public class StringUtilsTest {
@Test
public void testTruncate_StringIntInt() {
assertNull(StringUtils.truncate(null, 0, 12));
try {
StringUtils.truncate(null, -1, 0);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate(null, -10, -4);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate(null, Integer.MIN_VALUE, Integer.MIN_VALUE);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
assertThrows(
IllegalArgumentException.class, () -> StringUtils.truncate(null, -1, 0), "maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate(null, -10, -4),
"maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate(null, Integer.MIN_VALUE, Integer.MIN_VALUE),
"maxWith cannot be negative");
assertNull(StringUtils.truncate(null, 10, 12));
assertEquals("", StringUtils.truncate("", 0, 10));
assertEquals("", StringUtils.truncate("", 2, 10));
assertEquals("abc", StringUtils.truncate("abcdefghij", 0, 3));
assertEquals("fghij", StringUtils.truncate("abcdefghij", 5, 6));
assertEquals("", StringUtils.truncate("abcdefghij", 0, 0));
try {
StringUtils.truncate("abcdefghij", 0, -1);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", 0, -10);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", 0, -100);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", 1, -100);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", 0, Integer.MIN_VALUE);
fail("maxWith cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", -1, 0);
fail("offset cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", -10, 0);
fail("offset cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", -100, 1);
fail("offset cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", Integer.MIN_VALUE, 0);
fail("offset cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", -1, -1);
fail("offset cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", -10, -10);
fail("offset cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", -100, -100);
fail("offset cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
try {
StringUtils.truncate("abcdefghij", Integer.MIN_VALUE, Integer.MIN_VALUE);
fail("offset cannot be negative");
} catch (final Exception e) {
assertTrue(e instanceof IllegalArgumentException);
}
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", 0, -1),
"maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", 0, -10),
"maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", 0, -100),
"maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", 1, -100),
"maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", 0, Integer.MIN_VALUE),
"maxWith cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", -1, 0),
"offset cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", -10, 0),
"offset cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", -100, 1),
"offset cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", Integer.MIN_VALUE, 0),
"offset cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", -1, -1),
"offset cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", -10, -10),
"offset cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", -100, -100),
"offset cannot be negative");
assertThrows(
IllegalArgumentException.class,
() -> StringUtils.truncate("abcdefghij", Integer.MIN_VALUE, Integer.MIN_VALUE),
"offset cannot be negative");
final String raspberry = "raspberry peach";
assertEquals("peach", StringUtils.truncate(raspberry, 10, 15));
assertEquals("abcdefghij", StringUtils.truncate("abcdefghijklmno", 0, 10));
@ -2795,12 +2723,10 @@ public class StringUtilsTest {
assertEquals("AB", StringUtils.removeAll("A<__>\n<__>B", "(?s)<.*>"));
assertEquals("ABC123", StringUtils.removeAll("ABCabc123abc", "[a-z]"));
try {
StringUtils.removeAll("any", "{badRegexSyntax}");
fail("StringUtils.removeAll expecting PatternSyntaxException");
} catch (final PatternSyntaxException ex) {
// empty
}
assertThrows(
PatternSyntaxException.class,
() -> StringUtils.removeAll("any", "{badRegexSyntax}"),
"StringUtils.removeAll expecting PatternSyntaxException");
}
@Test
@ -2818,12 +2744,10 @@ public class StringUtilsTest {
assertEquals("ABCbc123", StringUtils.removeFirst("ABCabc123", "[a-z]"));
assertEquals("ABC123abc", StringUtils.removeFirst("ABCabc123abc", "[a-z]+"));
try {
StringUtils.removeFirst("any", "{badRegexSyntax}");
fail("StringUtils.removeFirst expecting PatternSyntaxException");
} catch (final PatternSyntaxException ex) {
// empty
}
assertThrows(
PatternSyntaxException.class,
() -> StringUtils.removeFirst("any", "{badRegexSyntax}"),
"StringUtils.removeFirst expecting PatternSyntaxException");
}
@Test

View File

@ -118,7 +118,7 @@ public class DiffResultTest {
@Test
public void testNullLhs() {
assertThrows(IllegalArgumentException.class,
() -> new DiffResult(null, SIMPLE_FALSE, SIMPLE_TRUE.diff(SIMPLE_FALSE).getDiffs(), SHORT_STYLE));
() -> new DiffResult(null, SIMPLE_FALSE, SIMPLE_TRUE.diff(SIMPLE_FALSE).getDiffs(), SHORT_STYLE));
}
@Test

View File

@ -17,7 +17,7 @@
package org.apache.commons.lang3.builder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import java.util.Date;
@ -91,11 +91,7 @@ public class JsonToStringStyleTest {
@Test
public void testChar() {
try {
new ToStringBuilder(base).append('A').toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append('A').toString());
assertEquals("{\"a\":\"A\"}", new ToStringBuilder(base).append("a", 'A')
.toString());
@ -108,11 +104,7 @@ public class JsonToStringStyleTest {
final Date now = new Date();
final Date afterNow = new Date(System.currentTimeMillis() + 1);
try {
new ToStringBuilder(base).append(now).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append(now).toString());
assertEquals("{\"now\":\"" + now.toString() +"\"}", new ToStringBuilder(base).append("now", now)
.toString());
@ -126,17 +118,10 @@ public class JsonToStringStyleTest {
final Integer i3 = Integer.valueOf(3);
final Integer i4 = Integer.valueOf(4);
try {
new ToStringBuilder(base).append((Object) null).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((Object) null).toString());
try {
new ToStringBuilder(base).append(i3).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append(i3).toString());
assertEquals("{\"a\":null}",
new ToStringBuilder(base).append("a", (Object) null).toString());
@ -146,63 +131,48 @@ public class JsonToStringStyleTest {
new ToStringBuilder(base).append("a", i3).append("b", i4)
.toString());
try {
new ToStringBuilder(base).append("a", i3, false).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append("a", i3, false).toString());
try {
new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class,
() -> new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString());
assertEquals(
"{\"a\":[]}",
new ToStringBuilder(base).append("a", new ArrayList<>(),
true).toString());
try {
new ToStringBuilder(base).append("a", new HashMap<>(), false).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class,
() -> new ToStringBuilder(base).append("a", new HashMap<>(), false).toString());
assertEquals(
"{\"a\":{}}",
new ToStringBuilder(base).append("a",
new HashMap<>(), true).toString());
try {
new ToStringBuilder(base).append("a", (Object) new String[0], false).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class,
() -> new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
assertEquals(
"{\"a\":[]}",
new ToStringBuilder(base).append("a", (Object) new String[0],
true).toString());
try {
new ToStringBuilder(base).append("a", (Object) new int[]{1, 2, 3}, false).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class,
() -> new ToStringBuilder(base).append("a", (Object) new int[]{1, 2, 3}, false).toString());
assertEquals(
"{\"a\":[1,2,3]}",
new ToStringBuilder(base).append("a",
(Object) new int[]{1, 2, 3}, true).toString());
try {
new ToStringBuilder(base).append("a", (Object) new String[]{"v", "x", "y", "z"}, false).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class,
() -> new ToStringBuilder(base).append("a", (Object) new String[]{"v", "x", "y", "z"}, false).toString());
assertEquals(
"{\"a\":[\"v\",\"x\",\"y\",\"z\"]}",
@ -252,12 +222,7 @@ public class JsonToStringStyleTest {
@Test
public void testLong() {
try {
new ToStringBuilder(base).append(3L).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append(3L).toString());
assertEquals("{\"a\":3}", new ToStringBuilder(base).append("a", 3L)
.toString());
@ -270,92 +235,48 @@ public class JsonToStringStyleTest {
public void testObjectArray() {
Object[] array = new Object[]{null, base, new int[]{3, 6}};
try {
new ToStringBuilder(base).append(array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append(array).toString());
try {
new ToStringBuilder(base).append((Object) array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((Object) array).toString());
array = null;
try {
new ToStringBuilder(base).append(array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((Object[]) null).toString());
try {
new ToStringBuilder(base).append((Object) array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testLongArray() {
long[] array = new long[]{1, 2, -3, 4};
try {
new ToStringBuilder(base).append(array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append(array).toString());
try {
new ToStringBuilder(base).append((Object) array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((long[]) null).toString());
try {
new ToStringBuilder(base).append(array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
try {
new ToStringBuilder(base).append((Object) array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((Object) array).toString());
}
@Test
public void testLongArrayArray() {
long[][] array = new long[][]{{1, 2}, null, {5}};
try {
new ToStringBuilder(base).append(array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append(array).toString());
try {
new ToStringBuilder(base).append((Object) array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((Object) array).toString());
array = null;
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((long[][]) null).toString());
try {
new ToStringBuilder(base).append(array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
try {
new ToStringBuilder(base).append((Object) array).toString();
fail("Should have generated UnsupportedOperationException");
} catch (final UnsupportedOperationException e) {
}
assertThrows(
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((Object) array).toString());
}
@Test

View File

@ -25,7 +25,6 @@ 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.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
@ -40,22 +39,18 @@ public class BackgroundInitializerTest {
*
* @param init the initializer to test
*/
private void checkInitialize(final BackgroundInitializerTestImpl init) {
try {
final Integer result = init.get();
assertEquals(1, result.intValue(), "Wrong result");
assertEquals(1, init.initializeCalls, "Wrong number of invocations");
assertNotNull(init.getFuture(), "No future");
} catch (final ConcurrentException cex) {
fail("Unexpected exception: " + cex);
}
private void checkInitialize(final BackgroundInitializerTestImpl init) throws ConcurrentException {
final Integer result = init.get();
assertEquals(1, result.intValue(), "Wrong result");
assertEquals(1, init.initializeCalls, "Wrong number of invocations");
assertNotNull(init.getFuture(), "No future");
}
/**
* Tests whether initialize() is invoked.
*/
@Test
public void testInitialize() {
public void testInitialize() throws ConcurrentException {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.start();
checkInitialize(init);
@ -75,7 +70,7 @@ public class BackgroundInitializerTest {
* Tests whether an external executor is correctly detected.
*/
@Test
public void testGetActiveExecutorExternal() throws InterruptedException {
public void testGetActiveExecutorExternal() throws InterruptedException, ConcurrentException {
final ExecutorService exec = Executors.newSingleThreadExecutor();
try {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(
@ -93,7 +88,7 @@ public class BackgroundInitializerTest {
* Tests getActiveExecutor() for a temporary executor.
*/
@Test
public void testGetActiveExecutorTemp() {
public void testGetActiveExecutorTemp() throws ConcurrentException {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.start();
assertNotNull(init.getActiveExecutor(), "No active executor");
@ -105,7 +100,7 @@ public class BackgroundInitializerTest {
* be created.
*/
@Test
public void testInitializeTempExecutor() {
public void testInitializeTempExecutor() throws ConcurrentException {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
assertTrue(init.start(), "Wrong result of start()");
checkInitialize(init);
@ -117,7 +112,7 @@ public class BackgroundInitializerTest {
* setExternalExecutor() method.
*/
@Test
public void testSetExternalExecutor() {
public void testSetExternalExecutor() throws ConcurrentException {
final ExecutorService exec = Executors.newCachedThreadPool();
try {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
@ -143,9 +138,7 @@ public class BackgroundInitializerTest {
init.start();
final ExecutorService exec = Executors.newSingleThreadExecutor();
try {
init.setExternalExecutor(exec);
fail("Could set executor after start()!");
} catch (final IllegalStateException istex) {
assertThrows(IllegalStateException.class, () -> init.setExternalExecutor(exec));
init.get();
} finally {
exec.shutdown();
@ -158,7 +151,7 @@ public class BackgroundInitializerTest {
* have an effect.
*/
@Test
public void testStartMultipleTimes() {
public void testStartMultipleTimes() throws ConcurrentException {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
assertTrue(init.start(), "Wrong result for start()");
for (int i = 0; i < 10; i++) {
@ -188,12 +181,8 @@ public class BackgroundInitializerTest {
final RuntimeException rex = new RuntimeException();
init.ex = rex;
init.start();
try {
init.get();
fail("Exception not thrown!");
} catch (final Exception ex) {
assertEquals(rex, ex, "Runtime exception not thrown");
}
Exception ex = assertThrows(Exception.class, init::get);
assertEquals(rex, ex, "Runtime exception not thrown");
}
/**
@ -206,12 +195,8 @@ public class BackgroundInitializerTest {
final Exception ex = new Exception();
init.ex = ex;
init.start();
try {
init.get();
fail("Exception not thrown!");
} catch (final ConcurrentException cex) {
assertEquals(ex, cex.getCause(), "Exception not thrown");
}
ConcurrentException cex = assertThrows(ConcurrentException.class, init::get);
assertEquals(ex, cex.getCause(), "Exception not thrown");
}
/**
@ -274,7 +259,7 @@ public class BackgroundInitializerTest {
* Tests isStarted() after the background task has finished.
*/
@Test
public void testIsStartedAfterGet() {
public void testIsStartedAfterGet() throws ConcurrentException {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.start();
checkInitialize(init);

View File

@ -23,7 +23,6 @@ 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 static org.junit.jupiter.api.Assertions.fail;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@ -108,12 +107,9 @@ public class ConcurrentUtilsTest {
@Test
public void testExtractCauseError() {
final Error err = new AssertionError("Test");
try {
ConcurrentUtils.extractCause(new ExecutionException(err));
fail("Error not thrown!");
} catch (final Error e) {
assertEquals(err, e, "Wrong error");
}
AssertionError e =
assertThrows(AssertionError.class, () -> ConcurrentUtils.extractCause(new ExecutionException(err)));
assertEquals(err, e, "Wrong error");
}
/**
@ -122,12 +118,8 @@ public class ConcurrentUtilsTest {
@Test
public void testExtractCauseUncheckedException() {
final RuntimeException rex = new RuntimeException("Test");
try {
ConcurrentUtils.extractCause(new ExecutionException(rex));
fail("Runtime exception not thrown!");
} catch (final RuntimeException r) {
assertEquals(rex, r, "Wrong exception");
}
RuntimeException r =
assertThrows(RuntimeException.class, () -> ConcurrentUtils.extractCause(new ExecutionException(rex)));
}
/**
@ -163,12 +155,8 @@ public class ConcurrentUtilsTest {
@Test
public void testExtractCauseUncheckedError() {
final Error err = new AssertionError("Test");
try {
ConcurrentUtils.extractCauseUnchecked(new ExecutionException(err));
fail("Error not thrown!");
} catch (final Error e) {
assertEquals(err, e, "Wrong error");
}
Error e = assertThrows(Error.class, () -> ConcurrentUtils.extractCauseUnchecked(new ExecutionException(err)));
assertEquals(err, e, "Wrong error");
}
/**
@ -177,12 +165,9 @@ public class ConcurrentUtilsTest {
@Test
public void testExtractCauseUncheckedUncheckedException() {
final RuntimeException rex = new RuntimeException("Test");
try {
ConcurrentUtils.extractCauseUnchecked(new ExecutionException(rex));
fail("Runtime exception not thrown!");
} catch (final RuntimeException r) {
assertEquals(rex, r, "Wrong exception");
}
RuntimeException r =
assertThrows(RuntimeException.class, () -> ConcurrentUtils.extractCauseUnchecked(new ExecutionException(rex)));
assertEquals(rex, r, "Wrong exception");
}
/**
@ -204,12 +189,8 @@ public class ConcurrentUtilsTest {
@Test
public void testHandleCauseError() throws ConcurrentException {
final Error err = new AssertionError("Test");
try {
ConcurrentUtils.handleCause(new ExecutionException(err));
fail("Error not thrown!");
} catch (final Error e) {
assertEquals(err, e, "Wrong error");
}
Error e = assertThrows(Error.class, () -> ConcurrentUtils.handleCause(new ExecutionException(err)));
assertEquals(err, e, "Wrong error");
}
/**
@ -220,12 +201,9 @@ public class ConcurrentUtilsTest {
@Test
public void testHandleCauseUncheckedException() throws ConcurrentException {
final RuntimeException rex = new RuntimeException("Test");
try {
ConcurrentUtils.handleCause(new ExecutionException(rex));
fail("Runtime exception not thrown!");
} catch (final RuntimeException r) {
assertEquals(rex, r, "Wrong exception");
}
RuntimeException r =
assertThrows(RuntimeException.class, () -> ConcurrentUtils.handleCause(new ExecutionException(rex)));
assertEquals(rex, r, "Wrong exception");
}
/**
@ -234,12 +212,9 @@ public class ConcurrentUtilsTest {
@Test
public void testHandleCauseChecked() {
final Exception ex = new Exception("Test");
try {
ConcurrentUtils.handleCause(new ExecutionException(ex));
fail("ConcurrentException not thrown!");
} catch (final ConcurrentException cex) {
assertEquals(ex, cex.getCause(), "Wrong cause");
}
ConcurrentException cex =
assertThrows(ConcurrentException.class, () -> ConcurrentUtils.handleCause(new ExecutionException(ex)));
assertEquals(ex, cex.getCause(), "Wrong cause");
}
/**
@ -261,12 +236,8 @@ public class ConcurrentUtilsTest {
@Test
public void testHandleCauseUncheckedError() {
final Error err = new AssertionError("Test");
try {
ConcurrentUtils.handleCauseUnchecked(new ExecutionException(err));
fail("Error not thrown!");
} catch (final Error e) {
assertEquals(err, e, "Wrong error");
}
Error e = assertThrows(Error.class, () -> ConcurrentUtils.handleCauseUnchecked(new ExecutionException(err)));
assertEquals(err, e, "Wrong error");
}
/**
@ -275,12 +246,9 @@ public class ConcurrentUtilsTest {
@Test
public void testHandleCauseUncheckedUncheckedException() {
final RuntimeException rex = new RuntimeException("Test");
try {
ConcurrentUtils.handleCauseUnchecked(new ExecutionException(rex));
fail("Runtime exception not thrown!");
} catch (final RuntimeException r) {
assertEquals(rex, r, "Wrong exception");
}
RuntimeException r =
assertThrows(RuntimeException.class, () -> ConcurrentUtils.handleCauseUnchecked(new ExecutionException(rex)));
assertEquals(rex, r, "Wrong exception");
}
/**
@ -289,12 +257,9 @@ public class ConcurrentUtilsTest {
@Test
public void testHandleCauseUncheckedChecked() {
final Exception ex = new Exception("Test");
try {
ConcurrentUtils.handleCauseUnchecked(new ExecutionException(ex));
fail("ConcurrentRuntimeException not thrown!");
} catch (final ConcurrentRuntimeException crex) {
assertEquals(ex, crex.getCause(), "Wrong cause");
}
ConcurrentRuntimeException crex =
assertThrows(ConcurrentRuntimeException.class, () -> ConcurrentUtils.handleCauseUnchecked(new ExecutionException(ex)));
assertEquals(ex, crex.getCause(), "Wrong cause");
}
/**
@ -386,12 +351,9 @@ public class ConcurrentUtilsTest {
final Exception cause = new Exception();
EasyMock.expect(init.get()).andThrow(new ConcurrentException(cause));
EasyMock.replay(init);
try {
ConcurrentUtils.initializeUnchecked(init);
fail("Exception not thrown!");
} catch (final ConcurrentRuntimeException crex) {
assertSame(cause, crex.getCause(), "Wrong cause");
}
ConcurrentRuntimeException crex =
assertThrows(ConcurrentRuntimeException.class, () -> ConcurrentUtils.initializeUnchecked(init));
assertSame(cause, crex.getCause(), "Wrong cause");
EasyMock.verify(init);
}
@ -567,13 +529,11 @@ public class ConcurrentUtilsTest {
final Exception ex = new Exception();
EasyMock.expect(init.get()).andThrow(new ConcurrentException(ex));
EasyMock.replay(init);
try {
ConcurrentUtils.createIfAbsentUnchecked(
new ConcurrentHashMap<>(), "test", init);
fail("Exception not thrown!");
} catch (final ConcurrentRuntimeException crex) {
assertEquals(ex, crex.getCause(), "Wrong cause");
}
ConcurrentRuntimeException crex =
assertThrows(
ConcurrentRuntimeException.class,
() -> ConcurrentUtils.createIfAbsentUnchecked(new ConcurrentHashMap<>(), "test", init));
assertEquals(ex, crex.getCause(), "Wrong cause");
EasyMock.verify(init);
}
}

View File

@ -24,7 +24,6 @@ import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
public class MemoizerTest {
@ -54,13 +53,7 @@ public class MemoizerTest {
expect(computable.compute(input)).andThrow(interruptedException);
replay(computable);
try {
memoizer.compute(input);
fail("Expected Throwable to be thrown!");
} catch (final Throwable expected) {
// Should always be thrown the first time
}
assertThrows(Throwable.class, () -> memoizer.compute(input));
assertThrows(IllegalStateException.class, () -> memoizer.compute(input));
}
@ -72,13 +65,7 @@ public class MemoizerTest {
expect(computable.compute(input)).andThrow(interruptedException);
replay(computable);
try {
memoizer.compute(input);
fail("Expected Throwable to be thrown!");
} catch (final Throwable expected) {
// Should always be thrown the first time
}
assertThrows(Throwable.class, () -> memoizer.compute(input));
assertThrows(IllegalStateException.class, () -> memoizer.compute(input));
}
@ -91,13 +78,7 @@ public class MemoizerTest {
expect(computable.compute(input)).andThrow(interruptedException).andReturn(answer);
replay(computable);
try {
memoizer.compute(input);
fail("Expected Throwable to be thrown!");
} catch (final Throwable expected) {
// Should always be thrown the first time
}
assertThrows(Throwable.class, () -> memoizer.compute(input));
assertEquals(answer, memoizer.compute(input));
}

View File

@ -21,7 +21,6 @@ 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 static org.junit.jupiter.api.Assertions.fail;
import java.util.Iterator;
import java.util.NoSuchElementException;
@ -194,13 +193,11 @@ public class MultiBackgroundInitializerTest {
@Test
public void testAddInitializerAfterStart() throws ConcurrentException {
initializer.start();
try {
initializer.addInitializer(CHILD_INIT,
new ChildBackgroundInitializer());
fail("Could add initializer after start()!");
} catch (final IllegalStateException istex) {
initializer.get();
}
assertThrows(
IllegalStateException.class,
() -> initializer.addInitializer(CHILD_INIT, new ChildBackgroundInitializer()),
"Could add initializer after start()!");
initializer.get();
}
/**
@ -276,12 +273,8 @@ public class MultiBackgroundInitializerTest {
child.ex = new RuntimeException();
initializer.addInitializer(CHILD_INIT, child);
initializer.start();
try {
initializer.get();
fail("Runtime exception not thrown!");
} catch (final Exception ex) {
assertEquals(child.ex, ex, "Wrong exception");
}
Exception ex = assertThrows(Exception.class, initializer::get);
assertEquals(child.ex, ex, "Wrong exception");
}
/**

View File

@ -22,7 +22,6 @@ 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 static org.junit.jupiter.api.Assertions.fail;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@ -379,11 +378,9 @@ public class ExceptionUtilsTest {
assertEquals(0, out.toString().length());
out = new ByteArrayOutputStream(1024);
try {
ExceptionUtils.printRootCauseStackTrace(withCause, (PrintStream) null);
fail();
} catch (final IllegalArgumentException ex) {
}
assertThrows(
IllegalArgumentException.class,
() -> ExceptionUtils.printRootCauseStackTrace(withCause, (PrintStream) null));
out = new ByteArrayOutputStream(1024);
final Throwable cause = createExceptionWithCause();
@ -405,11 +402,9 @@ public class ExceptionUtilsTest {
assertEquals(0, writer.getBuffer().length());
writer = new StringWriter(1024);
try {
ExceptionUtils.printRootCauseStackTrace(withCause, (PrintWriter) null);
fail();
} catch (final IllegalArgumentException ex) {
}
assertThrows(
IllegalArgumentException.class,
() -> ExceptionUtils.printRootCauseStackTrace(withCause, (PrintWriter) null));
writer = new StringWriter(1024);
final Throwable cause = createExceptionWithCause();
@ -542,30 +537,17 @@ public class ExceptionUtilsTest {
@Test
public void testThrow() {
final Exception expected = new InterruptedException();
try {
ExceptionUtils.rethrow(expected);
fail("Exception not thrown");
} catch (final Exception actual) {
assertSame(expected, actual);
}
Exception actual = assertThrows(Exception.class, () -> ExceptionUtils.rethrow(expected));
assertSame(expected, actual);
}
@Test
public void testCatchTechniques() {
try {
throwsCheckedException();
fail("Exception not thrown");
} catch (final Exception ioe) {
assertTrue(ioe instanceof IOException);
assertEquals(1, ExceptionUtils.getThrowableCount(ioe));
}
IOException ioe = assertThrows(IOException.class, ExceptionUtilsTest::throwsCheckedException);
assertEquals(1, ExceptionUtils.getThrowableCount(ioe));
try {
redeclareCheckedException();
fail("Exception not thrown");
} catch (final IOException ioe) {
assertEquals(1, ExceptionUtils.getThrowableCount(ioe));
}
ioe = assertThrows(IOException.class, ExceptionUtilsTest::redeclareCheckedException);
assertEquals(1, ExceptionUtils.getThrowableCount(ioe));
}
private static int redeclareCheckedException() throws IOException {
@ -586,41 +568,25 @@ public class ExceptionUtilsTest {
@Test
public void testWrapAndUnwrapError() {
try {
ExceptionUtils.wrapAndThrow(new OutOfMemoryError());
fail("Error not thrown");
} catch (final Throwable t) {
assertTrue(ExceptionUtils.hasCause(t, Error.class));
}
Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new OutOfMemoryError()));
assertTrue(ExceptionUtils.hasCause(t, Error.class));
}
@Test
public void testWrapAndUnwrapRuntimeException() {
try {
ExceptionUtils.wrapAndThrow(new IllegalArgumentException());
fail("RuntimeException not thrown");
} catch (final Throwable t) {
assertTrue(ExceptionUtils.hasCause(t, RuntimeException.class));
}
Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new IllegalArgumentException()));
assertTrue(ExceptionUtils.hasCause(t, RuntimeException.class));
}
@Test
public void testWrapAndUnwrapCheckedException() {
try {
ExceptionUtils.wrapAndThrow(new IOException());
fail("Checked Exception not thrown");
} catch (final Throwable t) {
assertTrue(ExceptionUtils.hasCause(t, IOException.class));
}
Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new IOException()));
assertTrue(ExceptionUtils.hasCause(t, IOException.class));
}
@Test
public void testWrapAndUnwrapThrowable() {
try {
ExceptionUtils.wrapAndThrow(new TestThrowable());
fail("Checked Exception not thrown");
} catch (final Throwable t) {
assertTrue(ExceptionUtils.hasCause(t, TestThrowable.class));
}
Throwable t = assertThrows(Throwable.class, () -> ExceptionUtils.wrapAndThrow(new TestThrowable()));
assertTrue(ExceptionUtils.hasCause(t, TestThrowable.class));
}
}

View File

@ -23,7 +23,6 @@ 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 static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
@ -119,30 +118,13 @@ public class FractionTest {
assertEquals(10, f.getDenominator());
// zero denominator
try {
f = Fraction.getFraction(1, 0);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(2, 0);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(-3, 0);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, 0));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(2, 0));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-3, 0));
// very large: can't represent as unsimplified fraction, although
try {
f = Fraction.getFraction(4, Integer.MIN_VALUE);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(1, Integer.MIN_VALUE);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(4, Integer.MIN_VALUE));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, Integer.MIN_VALUE));
}
@Test
@ -168,86 +150,37 @@ public class FractionTest {
assertEquals(2, f.getDenominator());
// negatives
try {
f = Fraction.getFraction(1, -6, -10);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(1, -6, -10);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(1, -6, -10);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, -6, -10));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, -6, -10));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, -6, -10));
// negative whole
f = Fraction.getFraction(-1, 6, 10);
assertEquals(-16, f.getNumerator());
assertEquals(10, f.getDenominator());
try {
f = Fraction.getFraction(-1, -6, 10);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(-1, 6, -10);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(-1, -6, -10);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, -6, 10));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, 6, -10));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, -6, -10));
// zero denominator
try {
f = Fraction.getFraction(0, 1, 0);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(1, 2, 0);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(-1, -3, 0);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(Integer.MAX_VALUE, 1, 2);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(-Integer.MAX_VALUE, 1, 2);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(0, 1, 0));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, 2, 0));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, -3, 0));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MAX_VALUE, 1, 2));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-Integer.MAX_VALUE, 1, 2));
// very large
f = Fraction.getFraction(-1, 0, Integer.MAX_VALUE);
assertEquals(-Integer.MAX_VALUE, f.getNumerator());
assertEquals(Integer.MAX_VALUE, f.getDenominator());
try {
// negative denominators not allowed in this constructor.
f = Fraction.getFraction(0, 4, Integer.MIN_VALUE);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(1, 1, Integer.MAX_VALUE);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(-1, 2, Integer.MAX_VALUE);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
// negative denominators not allowed in this constructor.
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(0, 4, Integer.MIN_VALUE));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, 1, Integer.MAX_VALUE));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(-1, 2, Integer.MAX_VALUE));
}
@Test
public void testReducedFactory_int_int() {
Fraction f = null;
@ -285,20 +218,9 @@ public class FractionTest {
assertEquals(5, f.getDenominator());
// zero denominator
try {
f = Fraction.getReducedFraction(1, 0);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getReducedFraction(2, 0);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getReducedFraction(-3, 0);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(1, 0));
assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(2, 0));
assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(-3, 0));
// reduced
f = Fraction.getReducedFraction(0, 2);
@ -328,10 +250,7 @@ public class FractionTest {
assertEquals(-(Integer.MIN_VALUE / 2), f.getDenominator());
// Can't reduce, negation will throw
try {
f = Fraction.getReducedFraction(-7, Integer.MIN_VALUE);
fail("Expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getReducedFraction(-7, Integer.MIN_VALUE));
// LANG-662
f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2);
@ -341,30 +260,13 @@ public class FractionTest {
@Test
public void testFactory_double() {
Fraction f = null;
try {
f = Fraction.getFraction(Double.NaN);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(Double.POSITIVE_INFINITY);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction(Double.NEGATIVE_INFINITY);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = Fraction.getFraction((double) Integer.MAX_VALUE + 1);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Double.NaN));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Double.POSITIVE_INFINITY));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Double.NEGATIVE_INFINITY));
assertThrows(ArithmeticException.class, () -> Fraction.getFraction((double) Integer.MAX_VALUE + 1));
// zero
f = Fraction.getFraction(0.0d);
Fraction f = Fraction.getFraction(0.0d);
assertEquals(0, f.getNumerator());
assertEquals(1, f.getDenominator());
@ -402,12 +304,8 @@ public class FractionTest {
Fraction f2 = null;
for (int i = 1; i <= 100; i++) { // denominator
for (int j = 1; j <= i; j++) { // numerator
try {
f = Fraction.getFraction((double) j / (double) i);
} catch (final ArithmeticException ex) {
System.err.println(j + " " + i);
throw ex;
}
f = Fraction.getFraction((double) j / (double) i);
f2 = Fraction.getReducedFraction(j, i);
assertEquals(f2.getNumerator(), f.getNumerator());
assertEquals(f2.getDenominator(), f.getDenominator());
@ -416,12 +314,7 @@ public class FractionTest {
// save time by skipping some tests! (
for (int i = 1001; i <= 10000; i+=SKIP) { // denominator
for (int j = 1; j <= i; j++) { // numerator
try {
f = Fraction.getFraction((double) j / (double) i);
} catch (final ArithmeticException ex) {
System.err.println(j + " " + i);
throw ex;
}
f = Fraction.getFraction((double) j / (double) i);
f2 = Fraction.getReducedFraction(j, i);
assertEquals(f2.getNumerator(), f.getNumerator());
assertEquals(f2.getDenominator(), f.getDenominator());
@ -455,20 +348,9 @@ public class FractionTest {
assertEquals(2, f.getNumerator());
assertEquals(3, f.getDenominator());
try {
f = Fraction.getFraction("2.3R");
fail("Expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
try {
f = Fraction.getFraction("2147483648"); // too big
fail("Expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
try {
f = Fraction.getFraction(".");
fail("Expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2.3R"));
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2147483648")); // too big
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("."));
}
@Test
@ -499,35 +381,12 @@ public class FractionTest {
assertEquals(-6, f.getNumerator());
assertEquals(4, f.getDenominator());
try {
f = Fraction.getFraction("2 3");
fail("expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
try {
f = Fraction.getFraction("a 3");
fail("expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
try {
f = Fraction.getFraction("2 b/4");
fail("expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
try {
f = Fraction.getFraction("2 ");
fail("expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
try {
f = Fraction.getFraction(" 3");
fail("expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
try {
f = Fraction.getFraction(" ");
fail("expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2 3"));
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("a 3"));
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2 b/4"));
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2 "));
assertThrows(NumberFormatException.class, () -> Fraction.getFraction(" 3"));
assertThrows(NumberFormatException.class, () -> Fraction.getFraction(" "));
}
@Test
@ -558,25 +417,10 @@ public class FractionTest {
assertEquals(2, f.getNumerator());
assertEquals(4, f.getDenominator());
try {
f = Fraction.getFraction("2/d");
fail("expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
try {
f = Fraction.getFraction("2e/3");
fail("expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
try {
f = Fraction.getFraction("2/");
fail("expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
try {
f = Fraction.getFraction("/");
fail("expecting NumberFormatException");
} catch (final NumberFormatException ex) {}
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2/d"));
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2e/3"));
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("2/"));
assertThrows(NumberFormatException.class, () -> Fraction.getFraction("/"));
}
@Test
@ -681,18 +525,8 @@ public class FractionTest {
assertEquals(-47, f.getNumerator());
assertEquals(15, f.getDenominator());
f = Fraction.getFraction(0, 3);
try {
f = f.invert();
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
// large values
f = Fraction.getFraction(Integer.MIN_VALUE, 1);
try {
f = f.invert();
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(0, 3).invert());
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).invert());
f = Fraction.getFraction(Integer.MAX_VALUE, 1);
f = f.invert();
@ -720,11 +554,7 @@ public class FractionTest {
assertEquals(Integer.MIN_VALUE+2, f.getNumerator());
assertEquals(Integer.MAX_VALUE, f.getDenominator());
f = Fraction.getFraction(Integer.MIN_VALUE, 1);
try {
f = f.negate();
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).negate());
}
@Test
@ -751,11 +581,7 @@ public class FractionTest {
assertEquals(Integer.MAX_VALUE, f.getNumerator());
assertEquals(1, f.getDenominator());
f = Fraction.getFraction(Integer.MIN_VALUE, 1);
try {
f = f.abs();
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).abs());
}
@Test
@ -829,14 +655,9 @@ public class FractionTest {
assertEquals(1, f.getDenominator());
// zero to negative powers should throw an exception
try {
f = f.pow(-1);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f = f.pow(Integer.MIN_VALUE);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
final Fraction fr = f;
assertThrows(ArithmeticException.class, () -> fr.pow(-1));
assertThrows(ArithmeticException.class, () -> fr.pow(Integer.MIN_VALUE));
// one to any power is still one.
f = Fraction.getFraction(1, 1);
@ -851,24 +672,12 @@ public class FractionTest {
f = f.pow(Integer.MIN_VALUE);
assertEquals(f, Fraction.ONE);
f = Fraction.getFraction(Integer.MAX_VALUE, 1);
try {
f = f.pow(2);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MAX_VALUE, 1).pow(2));
// Numerator growing too negative during the pow operation.
f = Fraction.getFraction(Integer.MIN_VALUE, 1);
try {
f = f.pow(3);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).pow(3));
f = Fraction.getFraction(65536, 1);
try {
f = f.pow(2);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(65536, 1).pow(2));
}
@Test
@ -928,14 +737,11 @@ public class FractionTest {
f1 = Fraction.getFraction(-1, 13*13*2*2);
f2 = Fraction.getFraction(-2, 13*17*2);
f = f1.add(f2);
assertEquals(13*13*17*2*2, f.getDenominator());
assertEquals(-17 - 2*13*2, f.getNumerator());
final Fraction fr = f1.add(f2);
assertEquals(13*13*17*2*2, fr.getDenominator());
assertEquals(-17 - 2*13*2, fr.getNumerator());
try {
f.add(null);
fail("expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {}
assertThrows(IllegalArgumentException.class, () -> fr.add(null));
// if this fraction is added naively, it will overflow.
// check that it doesn't.
@ -957,37 +763,23 @@ public class FractionTest {
assertEquals(Integer.MAX_VALUE, f.getNumerator());
assertEquals(1, f.getDenominator());
try {
f = f.add(Fraction.ONE); // should overflow
fail("expecting ArithmeticException but got: " + f.toString());
} catch (final ArithmeticException ex) {}
final Fraction overflower = f;
assertThrows(ArithmeticException.class, () -> overflower.add(Fraction.ONE)); // should overflow
// denominator should not be a multiple of 2 or 3 to trigger overflow
f1 = Fraction.getFraction(Integer.MIN_VALUE, 5);
f2 = Fraction.getFraction(-1,5);
try {
f = f1.add(f2); // should overflow
fail("expecting ArithmeticException but got: " + f.toString());
} catch (final ArithmeticException ex) {}
assertThrows(
ArithmeticException.class,
() -> Fraction.getFraction(Integer.MIN_VALUE, 5).add(Fraction.getFraction(-1,5)));
try {
f= Fraction.getFraction(-Integer.MAX_VALUE, 1);
f = f.add(f);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
final Fraction maxValue = Fraction.getFraction(-Integer.MAX_VALUE, 1);
assertThrows(ArithmeticException.class, () -> maxValue.add(maxValue));
try {
f= Fraction.getFraction(-Integer.MAX_VALUE, 1);
f = f.add(f);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
final Fraction negativeMaxValue = Fraction.getFraction(-Integer.MAX_VALUE, 1);
assertThrows(ArithmeticException.class, () -> negativeMaxValue.add(negativeMaxValue));
f1 = Fraction.getFraction(3,327680);
f2 = Fraction.getFraction(2,59049);
try {
f = f1.add(f2); // should overflow
fail("expecting ArithmeticException but got: " + f.toString());
} catch (final ArithmeticException ex) {}
final Fraction f3 = Fraction.getFraction(3,327680);
final Fraction f4 = Fraction.getFraction(2,59049);
assertThrows(ArithmeticException.class, () -> f3.add(f4)); // should overflow
}
@Test
@ -1043,10 +835,8 @@ public class FractionTest {
f = f2.subtract(f1);
assertSame(f2, f);
try {
f.subtract(null);
fail("expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {}
final Fraction fr = f;
assertThrows(IllegalArgumentException.class, () -> fr.subtract(null));
// if this fraction is subtracted naively, it will overflow.
// check that it doesn't.
@ -1068,39 +858,28 @@ public class FractionTest {
assertEquals(Integer.MAX_VALUE-1, f.getNumerator());
assertEquals(1, f.getDenominator());
try {
f1 = Fraction.getFraction(1, Integer.MAX_VALUE);
f2 = Fraction.getFraction(1, Integer.MAX_VALUE - 1);
// Should overflow
assertThrows(
ArithmeticException.class,
() -> Fraction.getFraction(1, Integer.MAX_VALUE).subtract(Fraction.getFraction(1, Integer.MAX_VALUE - 1)));
f = f1.subtract(f2);
fail("expecting ArithmeticException"); //should overflow
} catch (final ArithmeticException ex) {}
// denominator should not be a multiple of 2 or 3 to trigger overflow
f1 = Fraction.getFraction(Integer.MIN_VALUE, 5);
f2 = Fraction.getFraction(1,5);
try {
f = f1.subtract(f2); // should overflow
fail("expecting ArithmeticException but got: " + f.toString());
} catch (final ArithmeticException ex) {}
assertThrows(
ArithmeticException.class,
() -> Fraction.getFraction(Integer.MIN_VALUE, 5).subtract(Fraction.getFraction(1,5)));
try {
f= Fraction.getFraction(Integer.MIN_VALUE, 1);
f = f.subtract(Fraction.ONE);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(
ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).subtract(Fraction.ONE));
try {
f= Fraction.getFraction(Integer.MAX_VALUE, 1);
f = f.subtract(Fraction.ONE.negate());
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(
ArithmeticException.class,
() -> Fraction.getFraction(Integer.MAX_VALUE, 1).subtract(Fraction.ONE.negate()));
f1 = Fraction.getFraction(3,327680);
f2 = Fraction.getFraction(2,59049);
try {
f = f1.subtract(f2); // should overflow
fail("expecting ArithmeticException but got: " + f.toString());
} catch (final ArithmeticException ex) {}
// Should overflow
assertThrows(
ArithmeticException.class,
() -> Fraction.getFraction(3,327680).subtract(Fraction.getFraction(2,59049)));
}
@Test
@ -1154,22 +933,14 @@ public class FractionTest {
assertEquals(Integer.MIN_VALUE, f.getNumerator());
assertEquals(1, f.getDenominator());
try {
f.multiplyBy(null);
fail("expecting IllegalArgumentException");
} catch (final IllegalArgumentException ex) {}
final Fraction fr = f;
assertThrows(IllegalArgumentException.class, () -> fr.multiplyBy(null));
try {
f1 = Fraction.getFraction(1, Integer.MAX_VALUE);
f = f1.multiplyBy(f1); // should overflow
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
final Fraction fr1 = Fraction.getFraction(1, Integer.MAX_VALUE);
assertThrows(ArithmeticException.class, () -> fr1.multiplyBy(fr1));
try {
f1 = Fraction.getFraction(1, -Integer.MAX_VALUE);
f = f1.multiplyBy(f1); // should overflow
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
final Fraction fr2 = Fraction.getFraction(1, -Integer.MAX_VALUE);
assertThrows(ArithmeticException.class, () -> fr2.multiplyBy(fr2));
}
@Test
@ -1184,12 +955,7 @@ public class FractionTest {
assertEquals(3, f.getNumerator());
assertEquals(2, f.getDenominator());
f1 = Fraction.getFraction(3, 5);
f2 = Fraction.ZERO;
try {
f = f1.divideBy(f2);
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(3, 5).divideBy(Fraction.ZERO));
f1 = Fraction.getFraction(0, 5);
f2 = Fraction.getFraction(2, 7);
@ -1209,25 +975,17 @@ public class FractionTest {
f1 = Fraction.getFraction(Integer.MIN_VALUE, Integer.MAX_VALUE);
f2 = Fraction.getFraction(1, Integer.MAX_VALUE);
f = f1.divideBy(f2);
assertEquals(Integer.MIN_VALUE, f.getNumerator());
assertEquals(1, f.getDenominator());
final Fraction fr = f1.divideBy(f2);
assertEquals(Integer.MIN_VALUE, fr.getNumerator());
assertEquals(1, fr.getDenominator());
try {
f.divideBy(null);
fail("IllegalArgumentException");
} catch (final IllegalArgumentException ex) {}
assertThrows(IllegalArgumentException.class, () -> fr.divideBy(null));
try {
f1 = Fraction.getFraction(1, Integer.MAX_VALUE);
f = f1.divideBy(f1.invert()); // should overflow
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
try {
f1 = Fraction.getFraction(1, -Integer.MAX_VALUE);
f = f1.divideBy(f1.invert()); // should overflow
fail("expecting ArithmeticException");
} catch (final ArithmeticException ex) {}
final Fraction smallest = Fraction.getFraction(1, Integer.MAX_VALUE);
assertThrows(ArithmeticException.class, () -> smallest.divideBy(smallest.invert())); // Should overflow
final Fraction negative = Fraction.getFraction(1, -Integer.MAX_VALUE);
assertThrows(ArithmeticException.class, () -> negative.divideBy(negative.invert())); // Should overflow
}
@Test
@ -1275,10 +1033,8 @@ public class FractionTest {
f1 = Fraction.getFraction(3, 5);
assertTrue(f1.compareTo(f1) == 0);
try {
f1.compareTo(null);
fail("expecting NullPointerException");
} catch (final NullPointerException ex) {}
final Fraction fr = f1;
assertThrows(NullPointerException.class, () -> fr.compareTo(null));
f2 = Fraction.getFraction(2, 5);
assertTrue(f1.compareTo(f2) > 0);

View File

@ -17,8 +17,8 @@
package org.apache.commons.lang3.math;
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 static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
@ -55,46 +55,45 @@ public class IEEE754rUtilsTest {
@Test
public void testEnforceExceptions() {
try {
IEEE754rUtils.min( (float[]) null);
fail("IllegalArgumentException expected for null input");
} catch(final IllegalArgumentException iae) { /* expected */ }
assertThrows(
IllegalArgumentException.class,
() -> IEEE754rUtils.min( (float[]) null),
"IllegalArgumentException expected for null input");
try {
IEEE754rUtils.min();
fail("IllegalArgumentException expected for empty input");
} catch(final IllegalArgumentException iae) { /* expected */ }
assertThrows(
IllegalArgumentException.class,
() -> IEEE754rUtils.min(),
"IllegalArgumentException expected for empty input");
try {
IEEE754rUtils.max( (float[]) null);
fail("IllegalArgumentException expected for null input");
} catch(final IllegalArgumentException iae) { /* expected */ }
assertThrows(
IllegalArgumentException.class,
() -> IEEE754rUtils.max( (float[]) null),
"IllegalArgumentException expected for null input");
try {
IEEE754rUtils.max();
fail("IllegalArgumentException expected for empty input");
} catch(final IllegalArgumentException iae) { /* expected */ }
assertThrows(
IllegalArgumentException.class,
IEEE754rUtils::max,
"IllegalArgumentException expected for empty input");
try {
IEEE754rUtils.min( (double[]) null);
fail("IllegalArgumentException expected for null input");
} catch(final IllegalArgumentException iae) { /* expected */ }
assertThrows(
IllegalArgumentException.class,
() -> IEEE754rUtils.min( (double[]) null),
"IllegalArgumentException expected for null input");
try {
IEEE754rUtils.min(new double[0]);
fail("IllegalArgumentException expected for empty input");
} catch(final IllegalArgumentException iae) { /* expected */ }
assertThrows(
IllegalArgumentException.class,
() -> IEEE754rUtils.min(new double[0]),
"IllegalArgumentException expected for empty input");
try {
IEEE754rUtils.max( (double[]) null);
fail("IllegalArgumentException expected for null input");
} catch(final IllegalArgumentException iae) { /* expected */ }
try {
IEEE754rUtils.max(new double[0]);
fail("IllegalArgumentException expected for empty input");
} catch(final IllegalArgumentException iae) { /* expected */ }
assertThrows(
IllegalArgumentException.class,
() -> IEEE754rUtils.max( (double[]) null),
"IllegalArgumentException expected for null input");
assertThrows(
IllegalArgumentException.class,
() -> IEEE754rUtils.max(new double[0]),
"IllegalArgumentException expected for empty input");
}
@Test

View File

@ -616,12 +616,9 @@ public class NumberUtilsTest {
}
protected void testCreateFloatFailure(final String str) {
try {
final Float value = NumberUtils.createFloat(str);
fail("createFloat(\"" + str + "\") should have failed: " + value);
} catch (final NumberFormatException ex) {
// empty
}
assertThrows(
NumberFormatException.class,
() -> NumberUtils.createFloat(str), "createFloat(\"" + str + "\") should have failed.");
}
@Test
@ -636,12 +633,10 @@ public class NumberUtilsTest {
}
protected void testCreateDoubleFailure(final String str) {
try {
final Double value = NumberUtils.createDouble(str);
fail("createDouble(\"" + str + "\") should have failed: " + value);
} catch (final NumberFormatException ex) {
// empty
}
assertThrows(
NumberFormatException.class,
() -> NumberUtils.createDouble(str),
"createDouble(\"" + str + "\") should have failed.");
}
@Test
@ -656,12 +651,10 @@ public class NumberUtilsTest {
}
protected void testCreateIntegerFailure(final String str) {
try {
final Integer value = NumberUtils.createInteger(str);
fail("createInteger(\"" + str + "\") should have failed: " + value);
} catch (final NumberFormatException ex) {
// empty
}
assertThrows(
NumberFormatException.class,
() -> NumberUtils.createInteger(str),
"createInteger(\"" + str + "\") should have failed.");
}
@Test
@ -676,12 +669,10 @@ public class NumberUtilsTest {
}
protected void testCreateLongFailure(final String str) {
try {
final Long value = NumberUtils.createLong(str);
fail("createLong(\"" + str + "\") should have failed: " + value);
} catch (final NumberFormatException ex) {
// empty
}
assertThrows(
NumberFormatException.class,
() -> NumberUtils.createLong(str),
"createLong(\"" + str + "\") should have failed.");
}
@Test
@ -709,12 +700,10 @@ public class NumberUtilsTest {
}
protected void testCreateBigIntegerFailure(final String str) {
try {
final BigInteger value = NumberUtils.createBigInteger(str);
fail("createBigInteger(\"" + str + "\") should have failed: " + value);
} catch (final NumberFormatException ex) {
// empty
}
assertThrows(
NumberFormatException.class,
() -> NumberUtils.createBigInteger(str),
"createBigInteger(\"" + str + "\") should have failed.");
}
@Test
@ -735,12 +724,10 @@ public class NumberUtilsTest {
}
protected void testCreateBigDecimalFailure(final String str) {
try {
final BigDecimal value = NumberUtils.createBigDecimal(str);
fail("createBigDecimal(\"" + str + "\") should have failed: " + value);
} catch (final NumberFormatException ex) {
// empty
}
assertThrows(
NumberFormatException.class,
() -> NumberUtils.createBigDecimal(str),
"createBigDecimal(\"" + str + "\") should have failed.");
}
// min/max tests
@ -954,15 +941,13 @@ public class NumberUtilsTest {
@Test
public void testMaxDouble() {
final double[] d = null;
try {
NumberUtils.max(d);
fail("No exception was thrown for null input.");
} catch (final IllegalArgumentException ex) {}
assertThrows(
IllegalArgumentException.class, () -> NumberUtils.max(d), "No exception was thrown for null input.");
try {
NumberUtils.max(new double[0]);
fail("No exception was thrown for empty input.");
} catch (final IllegalArgumentException ex) {}
assertThrows(
IllegalArgumentException.class,
() -> NumberUtils.max(new double[0]),
"No exception was thrown for empty input.");
// TODO: JUnit Jupiter 5.3.1 doesn't support delta=0.
// This should be replaced when it is supported in JUnit Jupiter 5.4.

View File

@ -20,8 +20,8 @@ import org.junit.jupiter.api.Test;
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 static org.junit.jupiter.api.Assertions.fail;
/**
* JUnit tests.
@ -42,10 +42,7 @@ public class MutableShortTest {
assertEquals((short) 2, new MutableShort("2").shortValue());
try {
new MutableShort((Number)null);
fail();
} catch (final NullPointerException ex) {}
assertThrows(NullPointerException.class, () -> new MutableShort((Number)null));
}
@Test
@ -65,10 +62,7 @@ public class MutableShortTest {
mutNum.setValue(new MutableShort((short) 3));
assertEquals((short) 3, mutNum.shortValue());
assertEquals(Short.valueOf((short) 3), mutNum.getValue());
try {
mutNum.setValue(null);
fail();
} catch (final NullPointerException ex) {}
assertThrows(NullPointerException.class, () -> mutNum.setValue(null));
}
@Test
@ -108,10 +102,7 @@ public class MutableShortTest {
assertEquals((short) 0, mutNum.compareTo(new MutableShort((short) 0)));
assertEquals((short) +1, mutNum.compareTo(new MutableShort((short) -1)));
assertEquals((short) -1, mutNum.compareTo(new MutableShort((short) 1)));
try {
mutNum.compareTo(null);
fail();
} catch (final NullPointerException ex) {}
assertThrows(NullPointerException.class, () -> mutNum.compareTo(null));
}
@Test

View File

@ -20,8 +20,8 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
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 static org.junit.jupiter.api.Assertions.fail;
import java.lang.reflect.Constructor;
import java.util.Arrays;
@ -186,24 +186,15 @@ public class ConstructorUtilsTest {
TestBean.class, new Object[] { NumberUtils.DOUBLE_ONE },
new Class[] { Double.TYPE }).toString());
try {
ConstructorUtils.invokeExactConstructor(TestBean.class,
NumberUtils.BYTE_ONE);
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException e) {
}
try {
ConstructorUtils.invokeExactConstructor(TestBean.class,
NumberUtils.LONG_ONE);
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException e) {
}
try {
ConstructorUtils.invokeExactConstructor(TestBean.class,
Boolean.TRUE);
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException e) {
}
assertThrows(
NoSuchMethodException.class,
() -> ConstructorUtils.invokeExactConstructor(TestBean.class,NumberUtils.BYTE_ONE));
assertThrows(
NoSuchMethodException.class,
() -> ConstructorUtils.invokeExactConstructor(TestBean.class, NumberUtils.LONG_ONE));
assertThrows(
NoSuchMethodException.class,
() -> ConstructorUtils.invokeExactConstructor(TestBean.class, Boolean.TRUE));
}
@Test

View File

@ -28,7 +28,6 @@ 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.lang.reflect.Method;
import java.lang.reflect.Type;
@ -435,12 +434,7 @@ public class MethodUtilsTest {
assertEquals("foo(long...)", MethodUtils.invokeMethod(testBean, "foo",
1L, 2L));
try {
MethodUtils.invokeMethod(testBean, "foo",
1, 2);
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException expected) {
}
assertThrows(NoSuchMethodException.class, () -> MethodUtils.invokeMethod(testBean, "foo", 1, 2));
TestBean.verify(new ImmutablePair<>("String...", new String[]{"x", "y"}),
MethodUtils.invokeMethod(testBean, "varOverloadEcho", "x", "y"));
@ -471,23 +465,14 @@ public class MethodUtilsTest {
"foo", new Object[]{NumberUtils.DOUBLE_ONE},
new Class[]{Double.TYPE}));
try {
MethodUtils
.invokeExactMethod(testBean, "foo", NumberUtils.BYTE_ONE);
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException e) {
}
try {
MethodUtils
.invokeExactMethod(testBean, "foo", NumberUtils.LONG_ONE);
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException e) {
}
try {
MethodUtils.invokeExactMethod(testBean, "foo", Boolean.TRUE);
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException e) {
}
assertThrows(
NoSuchMethodException.class,
() -> MethodUtils.invokeExactMethod(testBean, "foo", NumberUtils.BYTE_ONE));
assertThrows(
NoSuchMethodException.class,
() -> MethodUtils.invokeExactMethod(testBean, "foo", NumberUtils.LONG_ONE));
assertThrows(NoSuchMethodException.class, () -> MethodUtils.invokeExactMethod(testBean, "foo", Boolean.TRUE));
}
@Test
@ -526,11 +511,8 @@ public class MethodUtilsTest {
TestBean.verify(new ImmutablePair<>("Number...", new Number[]{17, 23, 42}),
MethodUtils.invokeStaticMethod(TestBean.class, "varOverloadEchoStatic", 17, 23, 42));
try {
MethodUtils.invokeStaticMethod(TestBean.class, "does_not_exist");
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException e) {
}
assertThrows(
NoSuchMethodException.class, () -> MethodUtils.invokeStaticMethod(TestBean.class, "does_not_exist"));
}
@Test
@ -551,24 +533,15 @@ public class MethodUtilsTest {
TestBean.class, "bar", new Object[]{NumberUtils.DOUBLE_ONE},
new Class[]{Double.TYPE}));
try {
MethodUtils.invokeExactStaticMethod(TestBean.class, "bar",
NumberUtils.BYTE_ONE);
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException e) {
}
try {
MethodUtils.invokeExactStaticMethod(TestBean.class, "bar",
NumberUtils.LONG_ONE);
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException e) {
}
try {
MethodUtils.invokeExactStaticMethod(TestBean.class, "bar",
Boolean.TRUE);
fail("should throw NoSuchMethodException");
} catch (final NoSuchMethodException e) {
}
assertThrows(
NoSuchMethodException.class,
() -> MethodUtils.invokeExactStaticMethod(TestBean.class, "bar", NumberUtils.BYTE_ONE));
assertThrows(
NoSuchMethodException.class,
() -> MethodUtils.invokeExactStaticMethod(TestBean.class, "bar", NumberUtils.LONG_ONE));
assertThrows(
NoSuchMethodException.class,
() -> MethodUtils.invokeExactStaticMethod(TestBean.class, "bar", Boolean.TRUE));
}
@Test

View File

@ -20,7 +20,7 @@ package org.apache.commons.lang3.text;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.text.DecimalFormatSymbols;
import java.util.Arrays;
@ -165,47 +165,36 @@ public class StrBuilderAppendInsertTest {
sb.append("foo", 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append("bar", -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
final StrBuilder sb1 = sb;
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append("bar", -1, 1),
"append(char[], -1,) expected IndexOutOfBoundsException");
try {
sb.append("bar", 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append("bar", 3, 1),
"append(char[], 3,) expected IndexOutOfBoundsException");
try {
sb.append("bar", 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append("bar", 1, -1),
"append(char[],, -1) expected IndexOutOfBoundsException");
try {
sb.append("bar", 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append("bar", 1, 3),
"append(char[], 1, 3) expected IndexOutOfBoundsException");
try {
sb.append("bar", -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append("bar", -1, 3),
"append(char[], -1, 3) expected IndexOutOfBoundsException");
try {
sb.append("bar", 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append("bar", 4, 0),
"append(char[], 4, 0) expected IndexOutOfBoundsException");
sb.append("bar", 3, 0);
assertEquals("foo", sb.toString());
@ -228,47 +217,36 @@ public class StrBuilderAppendInsertTest {
sb.append(new StringBuilder("foo"), 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append(new StringBuilder("bar"), -1, 1);
fail("append(StringBuilder, -1,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
final StrBuilder sb1 = sb;
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuilder("bar"), -1, 1),
"append(StringBuilder, -1,) expected IndexOutOfBoundsException");
try {
sb.append(new StringBuilder("bar"), 3, 1);
fail("append(StringBuilder, 3,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuilder("bar"), 3, 1),
"append(StringBuilder, 3,) expected IndexOutOfBoundsException");
try {
sb.append(new StringBuilder("bar"), 1, -1);
fail("append(StringBuilder,, -1) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuilder("bar"), 1, -1),
"append(StringBuilder,, -1) expected IndexOutOfBoundsException");
try {
sb.append(new StringBuilder("bar"), 1, 3);
fail("append(StringBuilder, 1, 3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuilder("bar"), 1, 3),
"append(StringBuilder, 1, 3) expected IndexOutOfBoundsException");
try {
sb.append(new StringBuilder("bar"), -1, 3);
fail("append(StringBuilder, -1, 3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuilder("bar"), -1, 3),
"append(StringBuilder, -1, 3) expected IndexOutOfBoundsException");
try {
sb.append(new StringBuilder("bar"), 4, 0);
fail("append(StringBuilder, 4, 0) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuilder("bar"), 4, 0),
"append(StringBuilder, 4, 0) expected IndexOutOfBoundsException");
sb.append(new StringBuilder("bar"), 3, 0);
assertEquals("foo", sb.toString());
@ -309,47 +287,36 @@ public class StrBuilderAppendInsertTest {
sb.append(new StringBuffer("foo"), 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append(new StringBuffer("bar"), -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
final StrBuilder sb1 = sb;
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuffer("bar"), -1, 1),
"append(char[], -1,) expected IndexOutOfBoundsException");
try {
sb.append(new StringBuffer("bar"), 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuffer("bar"), 3, 1),
"append(char[], 3,) expected IndexOutOfBoundsException");
try {
sb.append(new StringBuffer("bar"), 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuffer("bar"), 1, -1),
"append(char[],, -1) expected IndexOutOfBoundsException");
try {
sb.append(new StringBuffer("bar"), 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuffer("bar"), 1, 3),
"append(char[], 1, 3) expected IndexOutOfBoundsException");
try {
sb.append(new StringBuffer("bar"), -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuffer("bar"), -1, 3),
"append(char[], -1, 3) expected IndexOutOfBoundsException");
try {
sb.append(new StringBuffer("bar"), 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StringBuffer("bar"), 4, 0),
"append(char[], 4, 0) expected IndexOutOfBoundsException");
sb.append(new StringBuffer("bar"), 3, 0);
assertEquals("foo", sb.toString());
@ -387,47 +354,36 @@ public class StrBuilderAppendInsertTest {
sb.append(new StrBuilder("foo"), 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append(new StrBuilder("bar"), -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
final StrBuilder sb1 = sb;
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StrBuilder("bar"), -1, 1),
"append(char[], -1,) expected IndexOutOfBoundsException");
try {
sb.append(new StrBuilder("bar"), 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StrBuilder("bar"), 3, 1),
"append(char[], 3,) expected IndexOutOfBoundsException");
try {
sb.append(new StrBuilder("bar"), 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StrBuilder("bar"), 1, -1),
"append(char[],, -1) expected IndexOutOfBoundsException");
try {
sb.append(new StrBuilder("bar"), 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StrBuilder("bar"), 1, 3),
"append(char[], 1, 3) expected IndexOutOfBoundsException");
try {
sb.append(new StrBuilder("bar"), -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StrBuilder("bar"), -1, 3),
"append(char[], -1, 3) expected IndexOutOfBoundsException");
try {
sb.append(new StrBuilder("bar"), 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new StrBuilder("bar"), 4, 0),
"append(char[], 4, 0) expected IndexOutOfBoundsException");
sb.append(new StrBuilder("bar"), 3, 0);
assertEquals("foo", sb.toString());
@ -462,47 +418,36 @@ public class StrBuilderAppendInsertTest {
sb.append(new char[]{'f', 'o', 'o'}, 0, 3);
assertEquals("foo", sb.toString());
try {
sb.append(new char[]{'b', 'a', 'r'}, -1, 1);
fail("append(char[], -1,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
final StrBuilder sb1 = sb;
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new char[]{'b', 'a', 'r'}, -1, 1),
"append(char[], -1,) expected IndexOutOfBoundsException");
try {
sb.append(new char[]{'b', 'a', 'r'}, 3, 1);
fail("append(char[], 3,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new char[]{'b', 'a', 'r'}, 3, 1),
"append(char[], 3,) expected IndexOutOfBoundsException");
try {
sb.append(new char[]{'b', 'a', 'r'}, 1, -1);
fail("append(char[],, -1) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new char[]{'b', 'a', 'r'}, 1, -1),
"append(char[],, -1) expected IndexOutOfBoundsException");
try {
sb.append(new char[]{'b', 'a', 'r'}, 1, 3);
fail("append(char[], 1, 3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new char[]{'b', 'a', 'r'}, 1, 3),
"append(char[], 1, 3) expected IndexOutOfBoundsException");
try {
sb.append(new char[]{'b', 'a', 'r'}, -1, 3);
fail("append(char[], -1, 3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new char[]{'b', 'a', 'r'}, -1, 3),
"append(char[], -1, 3) expected IndexOutOfBoundsException");
try {
sb.append(new char[]{'b', 'a', 'r'}, 4, 0);
fail("append(char[], 4, 0) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.append(new char[]{'b', 'a', 'r'}, 4, 0),
"append(char[], 4, 0) expected IndexOutOfBoundsException");
sb.append(new char[]{'b', 'a', 'r'}, 3, 0);
assertEquals("foo", sb.toString());
@ -1288,19 +1233,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, FOO);
fail("insert(-1, Object) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, FOO),
"insert(-1, Object) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, FOO);
fail("insert(7, Object) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, FOO),
"insert(7, Object) expected StringIndexOutOfBoundsException");
sb.insert(0, (Object) null);
assertEquals("barbaz", sb.toString());
@ -1312,19 +1253,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, "foo");
fail("insert(-1, String) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, "foo"),
"insert(-1, String) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, "foo");
fail("insert(7, String) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, "foo"),
"insert(7, String) expected StringIndexOutOfBoundsException");
sb.insert(0, (String) null);
assertEquals("barbaz", sb.toString());
@ -1336,19 +1273,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, new char[]{'f', 'o', 'o'});
fail("insert(-1, char[]) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, new char[]{'f', 'o', 'o'}),
"insert(-1, char[]) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, new char[]{'f', 'o', 'o'});
fail("insert(7, char[]) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, new char[]{'f', 'o', 'o'}),
"insert(7, char[]) expected StringIndexOutOfBoundsException");
sb.insert(0, (char[]) null);
assertEquals("barbaz", sb.toString());
@ -1363,19 +1296,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
fail("insert(-1, char[], 3, 3) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3),
"insert(-1, char[], 3, 3) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3);
fail("insert(7, char[], 3, 3) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 3, 3),
"insert(7, char[], 3, 3) expected StringIndexOutOfBoundsException");
sb.insert(0, null, 0, 0);
assertEquals("barbaz", sb.toString());
@ -1383,33 +1312,25 @@ public class StrBuilderAppendInsertTest {
sb.insert(0, new char[0], 0, 0);
assertEquals("barbaz", sb.toString());
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, -1, 3);
fail("insert(0, char[], -1, 3) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, -1, 3),
"insert(0, char[], -1, 3) expected StringIndexOutOfBoundsException");
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 10, 3);
fail("insert(0, char[], 10, 3) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 10, 3),
"insert(0, char[], 10, 3) expected StringIndexOutOfBoundsException");
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, -1);
fail("insert(0, char[], 0, -1) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, -1),
"insert(0, char[], 0, -1) expected StringIndexOutOfBoundsException");
try {
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 10);
fail("insert(0, char[], 0, 10) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 10),
"insert(0, char[], 0, 10) expected StringIndexOutOfBoundsException");
sb.insert(0, new char[]{'a', 'b', 'c', 'f', 'o', 'o', 'd', 'e', 'f'}, 0, 0);
assertEquals("barbaz", sb.toString());
@ -1421,19 +1342,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, true);
fail("insert(-1, boolean) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, true),
"insert(-1, boolean) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, true);
fail("insert(7, boolean) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, true),
"insert(7, boolean) expected StringIndexOutOfBoundsException");
sb.insert(0, true);
assertEquals("truebarbaz", sb.toString());
@ -1445,19 +1362,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, '!');
fail("insert(-1, char) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, '!'),
"insert(-1, char) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, '!');
fail("insert(7, char) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, '!'),
"insert(7, char) expected StringIndexOutOfBoundsException");
sb.insert(0, '!');
assertEquals("!barbaz", sb.toString());
@ -1466,19 +1379,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 0);
fail("insert(-1, int) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, 0),
"insert(-1, int) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, 0);
fail("insert(7, int) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, 0),
"insert(7, int) expected StringIndexOutOfBoundsException");
sb.insert(0, '0');
assertEquals("0barbaz", sb.toString());
@ -1487,19 +1396,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 1L);
fail("insert(-1, long) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, 1L),
"insert(-1, long) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, 1L);
fail("insert(7, long) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, 1L),
"insert(7, long) expected StringIndexOutOfBoundsException");
sb.insert(0, 1L);
assertEquals("1barbaz", sb.toString());
@ -1508,19 +1413,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 2.3F);
fail("insert(-1, float) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, 2.3F),
"insert(-1, float) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, 2.3F);
fail("insert(7, float) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, 2.3F),
"insert(7, float) expected StringIndexOutOfBoundsException");
sb.insert(0, 2.3F);
assertEquals("2.3barbaz", sb.toString());
@ -1529,19 +1430,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, 4.5D);
fail("insert(-1, double) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, 4.5D),
"insert(-1, double) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, 4.5D);
fail("insert(7, double) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, 4.5D),
"insert(7, double) expected StringIndexOutOfBoundsException");
sb.insert(0, 4.5D);
assertEquals("4.5barbaz", sb.toString());
@ -1555,19 +1452,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, FOO);
fail("insert(-1, Object) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, FOO),
"insert(-1, Object) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, FOO);
fail("insert(7, Object) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, FOO),
"insert(7, Object) expected StringIndexOutOfBoundsException");
sb.insert(0, (Object) null);
assertEquals("nullbarbaz", sb.toString());
@ -1579,19 +1472,15 @@ public class StrBuilderAppendInsertTest {
sb.append("barbaz");
assertEquals("barbaz", sb.toString());
try {
sb.insert(-1, "foo");
fail("insert(-1, String) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(-1, "foo"),
"insert(-1, String) expected StringIndexOutOfBoundsException");
try {
sb.insert(7, "foo");
fail("insert(7, String) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.insert(7, "foo"),
"insert(7, String) expected StringIndexOutOfBoundsException");
sb.insert(0, (String) null);
assertEquals("nullbarbaz", sb.toString());

View File

@ -25,8 +25,8 @@ 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 static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.io.Reader;
@ -267,12 +267,10 @@ public class StrBuilderTest {
assertEquals(33, sb.size());
assertTrue(sb.isEmpty() == false);
try {
sb.setLength(-1);
fail("setLength(-1) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.setLength(-1),
"setLength(-1) expected StringIndexOutOfBoundsException");
sb.setLength(33);
assertEquals(33, sb.capacity());
@ -322,12 +320,10 @@ public class StrBuilderTest {
sb.setLength(3); // lengthen
assertEquals("He\0", sb.toString());
try {
sb.setLength(-1);
fail("setLength(-1) expected StringIndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.setLength(-1),
"setLength(-1) expected StringIndexOutOfBoundsException");
}
//-----------------------------------------------------------------------
@ -400,62 +396,40 @@ public class StrBuilderTest {
@Test
public void testCharAt() {
final StrBuilder sb = new StrBuilder();
try {
sb.charAt(0);
fail("charAt(0) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
sb.charAt(-1);
fail("charAt(-1) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class, () -> sb.charAt(0), "charAt(0) expected IndexOutOfBoundsException");
assertThrows(
IndexOutOfBoundsException.class, () -> sb.charAt(-1), "charAt(-1) expected IndexOutOfBoundsException");
sb.append("foo");
assertEquals('f', sb.charAt(0));
assertEquals('o', sb.charAt(1));
assertEquals('o', sb.charAt(2));
try {
sb.charAt(-1);
fail("charAt(-1) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
sb.charAt(3);
fail("charAt(3) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class, () -> sb.charAt(-1), "charAt(-1) expected IndexOutOfBoundsException");
assertThrows(
IndexOutOfBoundsException.class, () -> sb.charAt(3), "charAt(3) expected IndexOutOfBoundsException");
}
//-----------------------------------------------------------------------
@Test
public void testSetCharAt() {
final StrBuilder sb = new StrBuilder();
try {
sb.setCharAt(0, 'f');
fail("setCharAt(0,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
try {
sb.setCharAt(-1, 'f');
fail("setCharAt(-1,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.setCharAt(0, 'f'),
"setCharAt(0,) expected IndexOutOfBoundsException");
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.setCharAt(-1, 'f'),
"setCharAt(-1,) expected IndexOutOfBoundsException");
sb.append("foo");
sb.setCharAt(0, 'b');
sb.setCharAt(1, 'a');
sb.setCharAt(2, 'r');
try {
sb.setCharAt(3, '!');
fail("setCharAt(3,) expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {
// expected
}
assertThrows(
IndexOutOfBoundsException.class,
() -> sb.setCharAt(3, '!'),
"setCharAt(3,) expected IndexOutOfBoundsException");
assertEquals("bar", sb.toString());
}
@ -466,10 +440,7 @@ public class StrBuilderTest {
sb.deleteCharAt(0);
assertEquals("bc", sb.toString());
try {
sb.deleteCharAt(1000);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> sb.deleteCharAt(1000));
}
//-----------------------------------------------------------------------
@ -509,17 +480,11 @@ public class StrBuilderTest {
a = sb.toCharArray(0, 1);
assertNotNull(a, "toCharArray(int,int) result is null");
try {
sb.toCharArray(-1, 5);
fail("no string index out of bound on -1");
} catch (final IndexOutOfBoundsException e) {
}
assertThrows(
IndexOutOfBoundsException.class, () -> sb.toCharArray(-1, 5), "no string index out of bound on -1");
try {
sb.toCharArray(6, 5);
fail("no string index out of bound on -1");
} catch (final IndexOutOfBoundsException e) {
}
assertThrows(
IndexOutOfBoundsException.class, () -> sb.toCharArray(6, 5), "no string index out of bound on -1");
}
@Test
@ -559,33 +524,14 @@ public class StrBuilderTest {
sb.getChars(0,5,a,0);
assertTrue(Arrays.equals(new char[] {'j','u','n','i','t'},a));
a = new char[5];
sb.getChars(0,2,a,3);
assertTrue(Arrays.equals(new char[] {0,0,0,'j','u'},a));
final char[] b = new char[5];
sb.getChars(0,2,b,3);
assertTrue(Arrays.equals(new char[] {0,0,0,'j','u'},b));
try {
sb.getChars(-1,0,a,0);
fail("no exception");
} catch (final IndexOutOfBoundsException e) {
}
try {
sb.getChars(0,-1,a,0);
fail("no exception");
} catch (final IndexOutOfBoundsException e) {
}
try {
sb.getChars(0,20,a,0);
fail("no exception");
} catch (final IndexOutOfBoundsException e) {
}
try {
sb.getChars(4,2,a,0);
fail("no exception");
} catch (final IndexOutOfBoundsException e) {
}
assertThrows(IndexOutOfBoundsException.class, () -> sb.getChars(-1,0,b,0));
assertThrows(IndexOutOfBoundsException.class, () -> sb.getChars(0,-1,b,0));
assertThrows(IndexOutOfBoundsException.class, () -> sb.getChars(0,20,b,0));
assertThrows(IndexOutOfBoundsException.class, () -> sb.getChars(4,2,b,0));
}
//-----------------------------------------------------------------------
@ -601,20 +547,9 @@ public class StrBuilderTest {
sb.delete(0, 1000);
assertEquals("", sb.toString());
try {
sb.delete(1, 2);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {}
try {
sb.delete(-1, 1);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {}
sb = new StrBuilder("anything");
try {
sb.delete(2, 1);
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> sb.delete(1, 2));
assertThrows(IndexOutOfBoundsException.class, () -> sb.delete(-1, 1));
assertThrows(IndexOutOfBoundsException.class, () -> new StrBuilder("anything").delete(2, 1));
}
//-----------------------------------------------------------------------
@ -757,23 +692,14 @@ public class StrBuilderTest {
sb.replace(0, 1000, "text");
assertEquals("text", sb.toString());
sb = new StrBuilder("atext");
sb.replace(1, 1, "ny");
assertEquals("anytext", sb.toString());
try {
sb.replace(2, 1, "anything");
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {}
StrBuilder sb1 = new StrBuilder("atext");
sb1.replace(1, 1, "ny");
assertEquals("anytext", sb1.toString());
assertThrows(IndexOutOfBoundsException.class, () -> sb1.replace(2, 1, "anything"));
sb = new StrBuilder();
try {
sb.replace(1, 2, "anything");
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {}
try {
sb.replace(-1, 1, "anything");
fail("Expected IndexOutOfBoundsException");
} catch (final IndexOutOfBoundsException e) {}
StrBuilder sb2 = new StrBuilder();
assertThrows(IndexOutOfBoundsException.class, () -> sb2.replace(1, 2, "anything"));
assertThrows(IndexOutOfBoundsException.class, () -> sb2.replace(-1, 1, "anything"));
}
//-----------------------------------------------------------------------
@ -1033,19 +959,17 @@ public class StrBuilderTest {
sb.replace(StrMatcher.stringMatcher("aa"), "-", 10, sb.length(), -1);
assertEquals("aaxaaaayaa", sb.toString());
sb = new StrBuilder("aaxaaaayaa");
try {
sb.replace(StrMatcher.stringMatcher("aa"), "-", 11, sb.length(), -1);
fail();
} catch (final IndexOutOfBoundsException ex) {}
assertEquals("aaxaaaayaa", sb.toString());
StrBuilder sb1 = new StrBuilder("aaxaaaayaa");
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.replace(StrMatcher.stringMatcher("aa"), "-", 11, sb1.length(), -1));
assertEquals("aaxaaaayaa", sb1.toString());
sb = new StrBuilder("aaxaaaayaa");
try {
sb.replace(StrMatcher.stringMatcher("aa"), "-", -1, sb.length(), -1);
fail();
} catch (final IndexOutOfBoundsException ex) {}
assertEquals("aaxaaaayaa", sb.toString());
StrBuilder sb2 = new StrBuilder("aaxaaaayaa");
assertThrows(
IndexOutOfBoundsException.class,
() -> sb2.replace(StrMatcher.stringMatcher("aa"), "-", -1, sb2.length(), -1));
assertEquals("aaxaaaayaa", sb2.toString());
}
@Test
@ -1094,12 +1018,11 @@ public class StrBuilderTest {
sb.replace(StrMatcher.stringMatcher("aa"), "-", 0, 1000, -1);
assertEquals("-x--y-", sb.toString());
sb = new StrBuilder("aaxaaaayaa");
try {
sb.replace(StrMatcher.stringMatcher("aa"), "-", 2, 1, -1);
fail();
} catch (final IndexOutOfBoundsException ex) {}
assertEquals("aaxaaaayaa", sb.toString());
StrBuilder sb1 = new StrBuilder("aaxaaaayaa");
assertThrows(
IndexOutOfBoundsException.class,
() -> sb1.replace(StrMatcher.stringMatcher("aa"), "-", 2, 1, -1));
assertEquals("aaxaaaayaa", sb1.toString());
}
@Test
@ -1202,28 +1125,16 @@ public class StrBuilderTest {
public void testSubSequenceIntInt() {
final StrBuilder sb = new StrBuilder ("hello goodbye");
// Start index is negative
try {
sb.subSequence(-1, 5);
fail();
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> sb.subSequence(-1, 5));
// End index is negative
try {
sb.subSequence(2, -1);
fail();
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> sb.subSequence(2, -1));
// End index greater than length()
try {
sb.subSequence(2, sb.length() + 1);
fail();
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> sb.subSequence(2, sb.length() + 1));
// Start index greater then end index
try {
sb.subSequence(3, 2);
fail();
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> sb.subSequence(3, 2));
// Normal cases
assertEquals ("hello", sb.subSequence(0, 5));
@ -1239,16 +1150,9 @@ public class StrBuilderTest {
assertEquals ("hello goodbye".substring(6), sb.substring(6));
assertEquals ("hello goodbye", sb.substring(0));
assertEquals ("hello goodbye".substring(0), sb.substring(0));
try {
sb.substring(-1);
fail ();
} catch (final IndexOutOfBoundsException e) {}
try {
sb.substring(15);
fail ();
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> sb.substring(-1));
assertThrows(IndexOutOfBoundsException.class, () -> sb.substring(15));
}
@Test
@ -1262,15 +1166,8 @@ public class StrBuilderTest {
assertEquals ("goodbye", sb.substring(6, 20));
try {
sb.substring(-1, 5);
fail();
} catch (final IndexOutOfBoundsException e) {}
try {
sb.substring(15, 20);
fail();
} catch (final IndexOutOfBoundsException e) {}
assertThrows(IndexOutOfBoundsException.class, () -> sb.substring(-1, 5));
assertThrows(IndexOutOfBoundsException.class, () -> sb.substring(15, 20));
}
// -----------------------------------------------------------------------
@ -1736,40 +1633,25 @@ public class StrBuilderTest {
reader.close();
assertTrue(reader.ready());
reader = sb.asReader();
array = new char[3];
try {
reader.read(array, -1, 0);
fail();
} catch (final IndexOutOfBoundsException ex) {}
try {
reader.read(array, 0, -1);
fail();
} catch (final IndexOutOfBoundsException ex) {}
try {
reader.read(array, 100, 1);
fail();
} catch (final IndexOutOfBoundsException ex) {}
try {
reader.read(array, 0, 100);
fail();
} catch (final IndexOutOfBoundsException ex) {}
try {
reader.read(array, Integer.MAX_VALUE, Integer.MAX_VALUE);
fail();
} catch (final IndexOutOfBoundsException ex) {}
final Reader r = sb.asReader();
final char[] arr = new char[3];
assertThrows(IndexOutOfBoundsException.class, () -> r.read(arr, -1, 0));
assertThrows(IndexOutOfBoundsException.class, () -> r.read(arr, 0, -1));
assertThrows(IndexOutOfBoundsException.class, () -> r.read(arr, 100, 1));
assertThrows(IndexOutOfBoundsException.class, () -> r.read(arr, 0, 100));
assertThrows(IndexOutOfBoundsException.class, () -> r.read(arr, Integer.MAX_VALUE, Integer.MAX_VALUE));
assertEquals(0, reader.read(array, 0, 0));
assertEquals(0, array[0]);
assertEquals(0, array[1]);
assertEquals(0, array[2]);
assertEquals(0, r.read(arr, 0, 0));
assertEquals(0, arr[0]);
assertEquals(0, arr[1]);
assertEquals(0, arr[2]);
reader.skip(9);
assertEquals(-1, reader.read(array, 0, 1));
r.skip(9);
assertEquals(-1, r.read(arr, 0, 1));
reader.reset();
r.reset();
array = new char[30];
assertEquals(9, reader.read(array, 0, 30));
assertEquals(9, r.read(array, 0, 30));
}
//-----------------------------------------------------------------------

View File

@ -19,7 +19,7 @@ package org.apache.commons.lang3.text;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.util.HashMap;
import java.util.Map;
@ -46,12 +46,7 @@ public class StrLookupTest {
assertEquals(System.getProperty("os.name"), StrLookup.systemPropertiesLookup().lookup("os.name"));
assertNull(StrLookup.systemPropertiesLookup().lookup(""));
assertNull(StrLookup.systemPropertiesLookup().lookup("other"));
try {
StrLookup.systemPropertiesLookup().lookup(null);
fail();
} catch (final NullPointerException ex) {
// expected
}
assertThrows(NullPointerException.class, () -> StrLookup.systemPropertiesLookup().lookup(null));
}
/**

View File

@ -21,8 +21,8 @@ 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.HashMap;
import java.util.Map;
@ -246,22 +246,18 @@ public class StrSubstitutorTest {
map.put("critterColor", "brown");
map.put("critterType", "${animal}");
StrSubstitutor sub = new StrSubstitutor(map);
try {
sub.replace("The ${animal} jumps over the ${target}.");
fail("Cyclic replacement was not detected!");
} catch (final IllegalStateException ex) {
// expected
}
assertThrows(
IllegalStateException.class,
() -> sub.replace("The ${animal} jumps over the ${target}."),
"Cyclic replacement was not detected!");
// also check even when default value is set.
map.put("critterType", "${animal:-fox}");
sub = new StrSubstitutor(map);
try {
sub.replace("The ${animal} jumps over the ${target}.");
fail("Cyclic replacement was not detected!");
} catch (final IllegalStateException ex) {
// expected
}
StrSubstitutor sub2 = new StrSubstitutor(map);
assertThrows(
IllegalStateException.class,
() -> sub2.replace("The ${animal} jumps over the ${target}."),
"Cyclic replacement was not detected!");
}
/**
@ -477,23 +473,13 @@ public class StrSubstitutorTest {
sub.setVariablePrefix("<<");
assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
try {
sub.setVariablePrefix(null);
fail();
} catch (final IllegalArgumentException ex) {
// expected
}
assertThrows(IllegalArgumentException.class, () -> sub.setVariablePrefix(null));
assertTrue(sub.getVariablePrefixMatcher() instanceof StrMatcher.StringMatcher);
final StrMatcher matcher = StrMatcher.commaMatcher();
sub.setVariablePrefixMatcher(matcher);
assertSame(matcher, sub.getVariablePrefixMatcher());
try {
sub.setVariablePrefixMatcher(null);
fail();
} catch (final IllegalArgumentException ex) {
// expected
}
assertThrows(IllegalArgumentException.class, () -> sub.setVariablePrefixMatcher(null));
assertSame(matcher, sub.getVariablePrefixMatcher());
}
@ -509,23 +495,13 @@ public class StrSubstitutorTest {
sub.setVariableSuffix("<<");
assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
try {
sub.setVariableSuffix(null);
fail();
} catch (final IllegalArgumentException ex) {
// expected
}
assertThrows(IllegalArgumentException.class, () -> sub.setVariableSuffix(null));
assertTrue(sub.getVariableSuffixMatcher() instanceof StrMatcher.StringMatcher);
final StrMatcher matcher = StrMatcher.commaMatcher();
sub.setVariableSuffixMatcher(matcher);
assertSame(matcher, sub.getVariableSuffixMatcher());
try {
sub.setVariableSuffixMatcher(null);
fail();
} catch (final IllegalArgumentException ex) {
// expected
}
assertThrows(IllegalArgumentException.class, () -> sub.setVariableSuffixMatcher(null));
assertSame(matcher, sub.getVariableSuffixMatcher());
}

View File

@ -22,8 +22,8 @@ import org.junit.jupiter.api.Test;
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 static org.junit.jupiter.api.Assertions.fail;
import java.util.Arrays;
import java.util.Collections;
@ -541,10 +541,7 @@ public class StrTokenizerTest {
assertFalse(tokenizer.hasPrevious());
assertNull(tokenizer.nextToken());
assertEquals(0, tokenizer.size());
try {
tokenizer.next();
fail();
} catch (final NoSuchElementException ex) {}
assertThrows(NoSuchElementException.class, tokenizer::next);
}
@Test
@ -805,25 +802,13 @@ public class StrTokenizerTest {
public void testIteration() {
final StrTokenizer tkn = new StrTokenizer("a b c");
assertFalse(tkn.hasPrevious());
try {
tkn.previous();
fail();
} catch (final NoSuchElementException ex) {}
assertThrows(NoSuchElementException.class, tkn::previous);
assertTrue(tkn.hasNext());
assertEquals("a", tkn.next());
try {
tkn.remove();
fail();
} catch (final UnsupportedOperationException ex) {}
try {
tkn.set("x");
fail();
} catch (final UnsupportedOperationException ex) {}
try {
tkn.add("y");
fail();
} catch (final UnsupportedOperationException ex) {}
assertThrows(UnsupportedOperationException.class, tkn::remove);
assertThrows(UnsupportedOperationException.class, () -> tkn.set("x"));
assertThrows(UnsupportedOperationException.class, () -> tkn.add("y"));
assertTrue(tkn.hasPrevious());
assertTrue(tkn.hasNext());
@ -835,10 +820,7 @@ public class StrTokenizerTest {
assertTrue(tkn.hasPrevious());
assertFalse(tkn.hasNext());
try {
tkn.next();
fail();
} catch (final NoSuchElementException ex) {}
assertThrows(NoSuchElementException.class, tkn::next);
assertTrue(tkn.hasPrevious());
assertFalse(tkn.hasNext());
}

View File

@ -18,7 +18,7 @@
package org.apache.commons.lang3.text.translate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
@ -67,15 +67,10 @@ public class NumericEntityUnescaperTest {
assertEquals(expected, result, "Failed to ignore unfinished entities (i.e. missing semi-colon)");
// fail it
neu = new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon);
input = "Test &#x30 not test";
try {
result = neu.translate(input);
fail("IllegalArgumentException expected");
} catch(final IllegalArgumentException iae) {
// expected
}
final NumericEntityUnescaper failingNeu =
new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon);
final String failingInput = "Test &#x30 not test";
assertThrows(IllegalArgumentException.class, () -> failingNeu.translate(failingInput));
}
}

View File

@ -18,7 +18,7 @@
package org.apache.commons.lang3.text.translate;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
@ -51,11 +51,9 @@ public class UnicodeUnescaperTest {
final UnicodeUnescaper uu = new UnicodeUnescaper();
final String input = "\\0047\\u006";
try {
uu.translate(input);
fail("A lack of digits in a Unicode escape sequence failed to throw an exception");
} catch(final IllegalArgumentException iae) {
// expected
}
assertThrows(
IllegalArgumentException.class,
() -> uu.translate(input),
"A lack of digits in a Unicode escape sequence failed to throw an exception");
}
}

View File

@ -20,7 +20,8 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Calendar;
import java.util.Date;
@ -47,114 +48,66 @@ public class DateUtilsFragmentTest {
@Test
public void testNullDate() {
try {
DateUtils.getFragmentInMilliseconds((Date) null, Calendar.MILLISECOND);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.getFragmentInMilliseconds((Date) null, Calendar.MILLISECOND));
try {
DateUtils.getFragmentInSeconds((Date) null, Calendar.MILLISECOND);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.getFragmentInSeconds((Date) null, Calendar.MILLISECOND));
try {
DateUtils.getFragmentInMinutes((Date) null, Calendar.MILLISECOND);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.getFragmentInMinutes((Date) null, Calendar.MILLISECOND));
try {
DateUtils.getFragmentInHours((Date) null, Calendar.MILLISECOND);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.getFragmentInHours((Date) null, Calendar.MILLISECOND));
try {
DateUtils.getFragmentInDays((Date) null, Calendar.MILLISECOND);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.getFragmentInDays((Date) null, Calendar.MILLISECOND));
}
@Test
public void testNullCalendar() {
try {
DateUtils.getFragmentInMilliseconds((Calendar) null, Calendar.MILLISECOND);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.getFragmentInMilliseconds((Calendar) null, Calendar.MILLISECOND));
try {
DateUtils.getFragmentInSeconds((Calendar) null, Calendar.MILLISECOND);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.getFragmentInSeconds((Calendar) null, Calendar.MILLISECOND));
try {
DateUtils.getFragmentInMinutes((Calendar) null, Calendar.MILLISECOND);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.getFragmentInMinutes((Calendar) null, Calendar.MILLISECOND));
try {
DateUtils.getFragmentInHours((Calendar) null, Calendar.MILLISECOND);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.getFragmentInHours((Calendar) null, Calendar.MILLISECOND));
try {
DateUtils.getFragmentInDays((Calendar) null, Calendar.MILLISECOND);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.getFragmentInDays((Calendar) null, Calendar.MILLISECOND));
}
@Test
public void testInvalidFragmentWithDate() {
try {
DateUtils.getFragmentInMilliseconds(aDate, 0);
fail();
} catch(final IllegalArgumentException iae) {}
try {
DateUtils.getFragmentInSeconds(aDate, 0);
fail();
} catch(final IllegalArgumentException iae) {}
try {
DateUtils.getFragmentInMinutes(aDate, 0);
fail();
} catch(final IllegalArgumentException iae) {}
try {
DateUtils.getFragmentInHours(aDate, 0);
fail();
} catch(final IllegalArgumentException iae) {}
try {
DateUtils.getFragmentInDays(aDate, 0);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInMilliseconds(aDate, 0));
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInSeconds(aDate, 0));
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInMinutes(aDate, 0));
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInHours(aDate, 0));
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInDays(aDate, 0));
}
@Test
public void testInvalidFragmentWithCalendar() {
try {
DateUtils.getFragmentInMilliseconds(aCalendar, 0);
fail();
} catch(final IllegalArgumentException iae) {}
try {
DateUtils.getFragmentInSeconds(aCalendar, 0);
fail();
} catch(final IllegalArgumentException iae) {}
try {
DateUtils.getFragmentInMinutes(aCalendar, 0);
fail();
} catch(final IllegalArgumentException iae) {}
try {
DateUtils.getFragmentInHours(aCalendar, 0);
fail();
} catch(final IllegalArgumentException iae) {}
try {
DateUtils.getFragmentInDays(aCalendar, 0);
fail();
} catch(final IllegalArgumentException iae) {}
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInMilliseconds(aCalendar, 0));
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInSeconds(aCalendar, 0));
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInMinutes(aCalendar, 0));
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInHours(aCalendar, 0));
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInDays(aCalendar, 0));
}
@Test

View File

@ -22,7 +22,6 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNotSame;
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.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
@ -366,10 +365,7 @@ public class DateUtilsTest {
final Date date = DateUtils.parseDate(dateStr, parsers);
assertEquals(cal.getTime(), date);
try {
DateUtils.parseDateStrictly(dateStr, parsers);
fail();
} catch (final ParseException ex) {}
assertThrows(ParseException.class, () -> DateUtils.parseDateStrictly(dateStr, parsers));
}
//-----------------------------------------------------------------------
@ -556,12 +552,10 @@ public class DateUtilsTest {
assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
assertDate(result, 2000, 1, 5, 4, 3, 2, 1);
try {
DateUtils.setMonths(BASE_DATE, 12);
fail("DateUtils.setMonths did not throw an expected IllegalArgumentException.");
} catch (final IllegalArgumentException e) {
}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.setMonths(BASE_DATE, 12),
"DateUtils.setMonths did not throw an expected IllegalArgumentException.");
}
// -----------------------------------------------------------------------
@ -577,12 +571,10 @@ public class DateUtilsTest {
assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
assertDate(result, 2000, 6, 29, 4, 3, 2, 1);
try {
DateUtils.setDays(BASE_DATE, 32);
fail("DateUtils.setDays did not throw an expected IllegalArgumentException.");
} catch (final IllegalArgumentException e) {
}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.setDays(BASE_DATE, 32),
"DateUtils.setDays did not throw an expected IllegalArgumentException.");
}
// -----------------------------------------------------------------------
@ -598,12 +590,10 @@ public class DateUtilsTest {
assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
assertDate(result, 2000, 6, 5, 23, 3, 2, 1);
try {
DateUtils.setHours(BASE_DATE, 24);
fail("DateUtils.setHours did not throw an expected IllegalArgumentException.");
} catch (final IllegalArgumentException e) {
}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.setHours(BASE_DATE, 24),
"DateUtils.setHours did not throw an expected IllegalArgumentException.");
}
// -----------------------------------------------------------------------
@ -619,12 +609,10 @@ public class DateUtilsTest {
assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
assertDate(result, 2000, 6, 5, 4, 59, 2, 1);
try {
DateUtils.setMinutes(BASE_DATE, 60);
fail("DateUtils.setMinutes did not throw an expected IllegalArgumentException.");
} catch (final IllegalArgumentException e) {
}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.setMinutes(BASE_DATE, 60),
"DateUtils.setMinutes did not throw an expected IllegalArgumentException.");
}
// -----------------------------------------------------------------------
@ -640,12 +628,10 @@ public class DateUtilsTest {
assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
assertDate(result, 2000, 6, 5, 4, 3, 59, 1);
try {
DateUtils.setSeconds(BASE_DATE, 60);
fail("DateUtils.setSeconds did not throw an expected IllegalArgumentException.");
} catch (final IllegalArgumentException e) {
}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.setSeconds(BASE_DATE, 60),
"DateUtils.setSeconds did not throw an expected IllegalArgumentException.");
}
// -----------------------------------------------------------------------
@ -661,12 +647,10 @@ public class DateUtilsTest {
assertDate(BASE_DATE, 2000, 6, 5, 4, 3, 2, 1);
assertDate(result, 2000, 6, 5, 4, 3, 2, 999);
try {
DateUtils.setMilliseconds(BASE_DATE, 1000);
fail("DateUtils.setMilliseconds did not throw an expected IllegalArgumentException.");
} catch (final IllegalArgumentException e) {
}
assertThrows(
IllegalArgumentException.class,
() -> DateUtils.setMilliseconds(BASE_DATE, 1000),
"DateUtils.setMilliseconds did not throw an expected IllegalArgumentException.");
}
//-----------------------------------------------------------------------
@ -686,12 +670,7 @@ public class DateUtilsTest {
@Test
public void testToCalendar() {
assertEquals(date1, DateUtils.toCalendar(date1).getTime(), "Failed to convert to a Calendar and back");
try {
DateUtils.toCalendar(null);
fail("Expected NullPointerException to be thrown");
} catch(final NullPointerException npe) {
// expected
}
assertThrows(NullPointerException.class, () -> DateUtils.toCalendar(null));
}
//-----------------------------------------------------------------------
@ -851,26 +830,11 @@ public class DateUtilsTest {
DateUtils.round((Object) dateAmPm4, Calendar.AM_PM),
"round ampm-4 failed");
try {
DateUtils.round((Date) null, Calendar.SECOND);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.round((Calendar) null, Calendar.SECOND);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.round((Object) null, Calendar.SECOND);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.round("", Calendar.SECOND);
fail();
} catch (final ClassCastException ex) {}
try {
DateUtils.round(date1, -9999);
fail();
} catch(final IllegalArgumentException ex) {}
assertThrows(IllegalArgumentException.class, () -> DateUtils.round((Date) null, Calendar.SECOND));
assertThrows(IllegalArgumentException.class, () -> DateUtils.round((Calendar) null, Calendar.SECOND));
assertThrows(IllegalArgumentException.class, () -> DateUtils.round((Object) null, Calendar.SECOND));
assertThrows(ClassCastException.class, () -> DateUtils.round("", Calendar.SECOND));
assertThrows(IllegalArgumentException.class, () -> DateUtils.round(date1, -9999));
assertEquals(dateTimeParser.parse("February 3, 2002 00:00:00.000"),
DateUtils.round((Object) calAmPm1, Calendar.AM_PM),
@ -1147,22 +1111,10 @@ public class DateUtilsTest {
DateUtils.truncate((Object) calAmPm4, Calendar.AM_PM),
"truncate ampm-4 failed");
try {
DateUtils.truncate((Date) null, Calendar.SECOND);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.truncate((Calendar) null, Calendar.SECOND);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.truncate((Object) null, Calendar.SECOND);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.truncate("", Calendar.SECOND);
fail();
} catch (final ClassCastException ex) {}
assertThrows(IllegalArgumentException.class, () -> DateUtils.truncate((Date) null, Calendar.SECOND));
assertThrows(IllegalArgumentException.class, () -> DateUtils.truncate((Calendar) null, Calendar.SECOND));
assertThrows(IllegalArgumentException.class, () -> DateUtils.truncate((Object) null, Calendar.SECOND));
assertThrows(ClassCastException.class, () -> DateUtils.truncate("", Calendar.SECOND));
// Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560
// Test truncate across beginning of daylight saving time
@ -1191,15 +1143,9 @@ public class DateUtilsTest {
final Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis
final GregorianCalendar endCal = new GregorianCalendar();
endCal.setTime(endOfTime);
try {
DateUtils.truncate(endCal, Calendar.DATE);
fail();
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> DateUtils.truncate(endCal, Calendar.DATE));
endCal.set(Calendar.YEAR, 280000001);
try {
DateUtils.truncate(endCal, Calendar.DATE);
fail();
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> DateUtils.truncate(endCal, Calendar.DATE));
endCal.set(Calendar.YEAR, 280000000);
final Calendar cal = DateUtils.truncate(endCal, Calendar.DATE);
assertEquals(0, cal.get(Calendar.HOUR));
@ -1445,27 +1391,11 @@ public class DateUtilsTest {
DateUtils.ceiling((Object) calAmPm4, Calendar.AM_PM),
"ceiling ampm-4 failed");
try {
DateUtils.ceiling((Date) null, Calendar.SECOND);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.ceiling((Calendar) null, Calendar.SECOND);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.ceiling((Object) null, Calendar.SECOND);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.ceiling("", Calendar.SECOND);
fail();
} catch (final ClassCastException ex) {}
try {
DateUtils.ceiling(date1, -9999);
fail();
} catch(final IllegalArgumentException ex) {}
assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling((Date) null, Calendar.SECOND));
assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling((Calendar) null, Calendar.SECOND));
assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling((Object) null, Calendar.SECOND));
assertThrows(ClassCastException.class, () -> DateUtils.ceiling("", Calendar.SECOND));
assertThrows(IllegalArgumentException.class, () -> DateUtils.ceiling(date1, -9999));
// Fix for http://issues.apache.org/bugzilla/show_bug.cgi?id=25560
// Test ceiling across the beginning of daylight saving time
@ -1532,15 +1462,9 @@ public class DateUtilsTest {
final Date endOfTime = new Date(Long.MAX_VALUE); // fyi: Sun Aug 17 07:12:55 CET 292278994 -- 807 millis
final GregorianCalendar endCal = new GregorianCalendar();
endCal.setTime(endOfTime);
try {
DateUtils.ceiling(endCal, Calendar.DATE);
fail();
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> DateUtils.ceiling(endCal, Calendar.DATE));
endCal.set(Calendar.YEAR, 280000001);
try {
DateUtils.ceiling(endCal, Calendar.DATE);
fail();
} catch (final ArithmeticException ex) {}
assertThrows(ArithmeticException.class, () -> DateUtils.ceiling(endCal, Calendar.DATE));
endCal.set(Calendar.YEAR, 280000000);
final Calendar cal = DateUtils.ceiling(endCal, Calendar.DATE);
assertEquals(0, cal.get(Calendar.HOUR));
@ -1553,25 +1477,14 @@ public class DateUtilsTest {
*/
@Test
public void testIteratorEx() throws Exception {
try {
DateUtils.iterator(Calendar.getInstance(), -9999);
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER);
fail();
} catch (final IllegalArgumentException ex) {}
try {
DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER);
fail();
} catch (final ClassCastException ex) {}
assertThrows(IllegalArgumentException.class, () -> DateUtils.iterator(Calendar.getInstance(), -9999));
assertThrows
(IllegalArgumentException.class, () -> DateUtils.iterator((Date) null, DateUtils.RANGE_WEEK_CENTER));
assertThrows
(IllegalArgumentException.class, () -> DateUtils.iterator((Calendar) null, DateUtils.RANGE_WEEK_CENTER));
assertThrows
(IllegalArgumentException.class, () -> DateUtils.iterator((Object) null, DateUtils.RANGE_WEEK_CENTER));
assertThrows(ClassCastException.class, () -> DateUtils.iterator("", DateUtils.RANGE_WEEK_CENTER));
}
/**
@ -1607,17 +1520,12 @@ public class DateUtilsTest {
it = DateUtils.iterator((Object) now, DateUtils.RANGE_WEEK_CENTER);
assertWeekIterator(it, centered);
it = DateUtils.iterator((Object) now.getTime(), DateUtils.RANGE_WEEK_CENTER);
assertWeekIterator(it, centered);
try {
it.next();
fail();
} catch (final NoSuchElementException ex) {}
it = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER);
it.next();
try {
it.remove();
} catch( final UnsupportedOperationException ex) {}
Iterator<?> it2 = DateUtils.iterator((Object) now.getTime(), DateUtils.RANGE_WEEK_CENTER);
assertWeekIterator(it2, centered);
assertThrows(NoSuchElementException.class, it2::next);
Iterator<?> it3 = DateUtils.iterator(now, DateUtils.RANGE_WEEK_CENTER);
it3.next();
assertThrows(UnsupportedOperationException.class, it3::remove);
now.add(Calendar.DATE,1);
}

View File

@ -335,34 +335,27 @@ public class FastDateParserTest {
final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
final DateParser fdf = getInstance(format, locale);
try {
checkParse(locale, cal, sdf, fdf);
} catch(final ParseException ex) {
fail("Locale "+locale+ " failed with "+format+" era "+(eraBC?"BC":"AD")+"\n" + trimMessage(ex.toString()));
}
// If parsing fails, a ParseException will be thrown and the test will fail
checkParse(locale, cal, sdf, fdf);
}
}
@Test
public void testJpLocales() {
public void testJpLocales() throws ParseException {
final Calendar cal= Calendar.getInstance(GMT);
cal.clear();
cal.set(2003, Calendar.FEBRUARY, 10);
cal.set(Calendar.ERA, GregorianCalendar.BC);
final Locale locale = LocaleUtils.toLocale("zh"); {
// ja_JP_JP cannot handle dates before 1868 properly
final Locale locale = LocaleUtils.toLocale("zh");
// ja_JP_JP cannot handle dates before 1868 properly
final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale);
final DateParser fdf = getInstance(LONG_FORMAT, locale);
final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale);
final DateParser fdf = getInstance(LONG_FORMAT, locale);
try {
checkParse(locale, cal, sdf, fdf);
} catch(final ParseException ex) {
fail("Locale "+locale+ " failed with "+LONG_FORMAT+"\n" + trimMessage(ex.toString()));
}
}
// If parsing fails, a ParseException will be thrown and the test will fail
checkParse(locale, cal, sdf, fdf);
}
private String trimMessage(final String msg) {
@ -668,12 +661,7 @@ public class FastDateParserTest {
final TimeZone kst = TimeZone.getTimeZone("KST");
final DateParser fdp = getInstance("yyyyMMdd", kst, Locale.KOREA);
try {
fdp.parse("2015");
fail("expected parse exception");
} catch (final ParseException pe) {
// expected parse exception
}
assertThrows(ParseException.class, () -> fdp.parse("2015"));
// Wed Apr 29 00:00:00 KST 2015
Date actual = fdp.parse("20150429");

View File

@ -27,13 +27,12 @@ import java.util.Locale;
import java.util.TimeZone;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.fail;
class FastDateParser_TimeZoneStrategyTest {
@ParameterizedTest
@MethodSource("java.util.Locale#getAvailableLocales")
void testTimeZoneStrategyPattern(final Locale locale) {
void testTimeZoneStrategyPattern(final Locale locale) throws ParseException {
final FastDateParser parser = new FastDateParser("z", TimeZone.getDefault(), locale);
final String[][] zones = DateFormatSymbols.getInstance(locale).getZoneStrings();
for (final String[] zone : zones) {
@ -42,17 +41,8 @@ class FastDateParser_TimeZoneStrategyTest {
if (tzDisplay == null) {
break;
}
try {
parser.parse(tzDisplay);
} catch (final Exception ex) {
fail("'" + tzDisplay + "'"
+ " Locale: '" + locale.getDisplayName() + "'"
+ " TimeZone: " + zone[0]
+ " offset: " + t
+ " defaultLocale: " + Locale.getDefault()
+ " defaultTimeZone: " + TimeZone.getDefault().getDisplayName()
);
}
// An exception will be thrown and the test will fail if parsing isn't successful
parser.parse(tzDisplay);
}
}
}

View File

@ -18,8 +18,8 @@ package org.apache.commons.lang3.time;
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 static org.junit.jupiter.api.Assertions.fail;
import java.util.concurrent.TimeUnit;
@ -167,105 +167,79 @@ public class StopWatchTest {
@Test
public void testBadStates() {
final StopWatch watch = new StopWatch();
try {
watch.stop();
fail("Calling stop on an unstarted StopWatch should throw an exception. ");
} catch (final IllegalStateException ise) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::stop,
"Calling stop on an unstarted StopWatch should throw an exception. ");
try {
watch.suspend();
fail("Calling suspend on an unstarted StopWatch should throw an exception. ");
} catch (final IllegalStateException ise) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::suspend,
"Calling suspend on an unstarted StopWatch should throw an exception. ");
try {
watch.split();
fail("Calling split on a non-running StopWatch should throw an exception. ");
} catch (final IllegalStateException ise) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::split,
"Calling split on a non-running StopWatch should throw an exception. ");
try {
watch.unsplit();
fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
} catch (final IllegalStateException ise) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::unsplit,
"Calling unsplit on an unsplit StopWatch should throw an exception. ");
try {
watch.resume();
fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
} catch (final IllegalStateException ise) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::resume,
"Calling resume on an unsuspended StopWatch should throw an exception. ");
watch.start();
try {
watch.start();
fail("Calling start on a started StopWatch should throw an exception. ");
} catch (final IllegalStateException ise) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::start,
"Calling start on a started StopWatch should throw an exception. ");
try {
watch.unsplit();
fail("Calling unsplit on an unsplit StopWatch should throw an exception. ");
} catch (final IllegalStateException ise) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::unsplit,
"Calling unsplit on an unsplit StopWatch should throw an exception. ");
try {
watch.getSplitTime();
fail("Calling getSplitTime on an unsplit StopWatch should throw an exception. ");
} catch (final IllegalStateException ise) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::getSplitTime,
"Calling getSplitTime on an unsplit StopWatch should throw an exception. ");
try {
watch.resume();
fail("Calling resume on an unsuspended StopWatch should throw an exception. ");
} catch (final IllegalStateException ise) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::resume,
"Calling resume on an unsuspended StopWatch should throw an exception. ");
watch.stop();
try {
watch.start();
fail("Calling start on a stopped StopWatch should throw an exception as it needs to be reset. ");
} catch (final IllegalStateException ise) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::start,
"Calling start on a stopped StopWatch should throw an exception as it needs to be reset. ");
}
@Test
public void testGetStartTime() {
final long beforeStopWatch = System.currentTimeMillis();
final StopWatch watch = new StopWatch();
try {
watch.getStartTime();
fail("Calling getStartTime on an unstarted StopWatch should throw an exception");
} catch (final IllegalStateException expected) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::getStartTime,
"Calling getStartTime on an unstarted StopWatch should throw an exception");
watch.start();
try {
watch.getStartTime();
assertTrue(watch.getStartTime() >= beforeStopWatch);
} catch (final IllegalStateException ex) {
fail("Start time should be available: " + ex.getMessage());
}
watch.getStartTime();
assertTrue(watch.getStartTime() >= beforeStopWatch);
watch.reset();
try {
watch.getStartTime();
fail("Calling getStartTime on a reset, but unstarted StopWatch should throw an exception");
} catch (final IllegalStateException expected) {
// expected
}
assertThrows(
IllegalStateException.class,
watch::getStartTime,
"Calling getStartTime on a reset, but unstarted StopWatch should throw an exception");
}
@Test