Add WhitespaceAround and WhitespaceAroundCheck

This commit is contained in:
Gary Gregory 2024-05-04 16:33:20 -04:00
parent 3d5c928656
commit 8e03321d14
49 changed files with 1069 additions and 1392 deletions

View File

@ -332,7 +332,7 @@ public class Streams {
* element to determine if it should be included. * element to determine if it should be included.
* @return the new stream * @return the new stream
*/ */
public FailableStream<O> filter(final FailablePredicate<O, ?> predicate){ public FailableStream<O> filter(final FailablePredicate<O, ?> predicate) {
assertNotTerminated(); assertNotTerminated();
stream = stream.filter(Functions.asPredicate(predicate)); stream = stream.filter(Functions.asPredicate(predicate));
return this; return this;

View File

@ -361,7 +361,7 @@ public class StringUtils {
if (strLen - offset < maxWidth - abbrevMarkerLength) { if (strLen - offset < maxWidth - abbrevMarkerLength) {
offset = strLen - (maxWidth - abbrevMarkerLength); offset = strLen - (maxWidth - abbrevMarkerLength);
} }
if (offset <= abbrevMarkerLength+1) { if (offset <= abbrevMarkerLength + 1) {
return str.substring(0, maxWidth - abbrevMarkerLength) + abbrevMarker; return str.substring(0, maxWidth - abbrevMarkerLength) + abbrevMarker;
} }
if (maxWidth < minAbbrevWidthOffset) { if (maxWidth < minAbbrevWidthOffset) {
@ -403,17 +403,13 @@ public class StringUtils {
* @since 2.5 * @since 2.5
*/ */
public static String abbreviateMiddle(final String str, final String middle, final int length) { public static String abbreviateMiddle(final String str, final String middle, final int length) {
if (isAnyEmpty(str, middle) || length >= str.length() || length < middle.length()+2) { if (isAnyEmpty(str, middle) || length >= str.length() || length < middle.length() + 2) {
return str; return str;
} }
final int targetSting = length - middle.length();
final int targetSting = length-middle.length(); final int startOffset = targetSting / 2 + targetSting % 2;
final int startOffset = targetSting/2+targetSting%2; final int endOffset = str.length() - targetSting / 2;
final int endOffset = str.length()-targetSting/2; return str.substring(0, startOffset) + middle + str.substring(endOffset);
return str.substring(0, startOffset) +
middle +
str.substring(endOffset);
} }
/** /**
@ -9393,7 +9389,7 @@ public class StringUtils {
* the string to be wrapped, may be {@code null} * the string to be wrapped, may be {@code null}
* @param wrapWith * @param wrapWith
* the char that will wrap {@code str} * the char that will wrap {@code str}
* @return the wrapped string, or {@code null} if {@code str==null} * @return the wrapped string, or {@code null} if {@code str == null}
* @since 3.4 * @since 3.4
*/ */
public static String wrap(final String str, final char wrapWith) { public static String wrap(final String str, final char wrapWith) {
@ -9463,7 +9459,7 @@ public class StringUtils {
* the string to be wrapped, may be {@code null} * the string to be wrapped, may be {@code null}
* @param wrapWith * @param wrapWith
* the char that will wrap {@code str} * the char that will wrap {@code str}
* @return the wrapped string, or {@code null} if {@code str==null} * @return the wrapped string, or {@code null} if {@code str == null}
* @since 3.5 * @since 3.5
*/ */
public static String wrapIfMissing(final String str, final char wrapWith) { public static String wrapIfMissing(final String str, final char wrapWith) {
@ -9513,7 +9509,7 @@ public class StringUtils {
* the string to be wrapped, may be {@code null} * the string to be wrapped, may be {@code null}
* @param wrapWith * @param wrapWith
* the string that will wrap {@code str} * the string that will wrap {@code str}
* @return the wrapped string, or {@code null} if {@code str==null} * @return the wrapped string, or {@code null} if {@code str == null}
* @since 3.5 * @since 3.5
*/ */
public static String wrapIfMissing(final String str, final String wrapWith) { public static String wrapIfMissing(final String str, final String wrapWith) {

View File

@ -51,7 +51,7 @@ import org.apache.commons.lang3.ClassUtils;
* <code>Person@7f54[ <br> * <code>Person@7f54[ <br>
* &nbsp; name=Stephen, <br> * &nbsp; name=Stephen, <br>
* &nbsp; age=29, <br> * &nbsp; age=29, <br>
* &nbsp; smoker=false, <br> * &nbsp; smokealse, <br>
* &nbsp; job=Job@43cd2[ <br> * &nbsp; job=Job@43cd2[ <br>
* &nbsp; &nbsp; title=Manager <br> * &nbsp; &nbsp; title=Manager <br>
* &nbsp; ] <br> * &nbsp; ] <br>

View File

@ -240,5 +240,7 @@ public class ComparableUtils {
return ObjectUtils.compare(comparable1, comparable2, true) < 0 ? comparable1 : comparable2; return ObjectUtils.compare(comparable1, comparable2, true) < 0 ? comparable1 : comparable2;
} }
private ComparableUtils() {} private ComparableUtils() {
// empty
}
} }

View File

@ -30,7 +30,7 @@ import java.util.function.IntConsumer;
public interface BooleanConsumer { public interface BooleanConsumer {
/** NOP singleton */ /** NOP singleton */
BooleanConsumer NOP = t -> {/* NOP */}; BooleanConsumer NOP = t -> { /* NOP */ };
/** /**
* Returns The NOP singleton. * Returns The NOP singleton.

View File

@ -33,7 +33,7 @@ public interface FailableBiConsumer<T, U, E extends Throwable> {
/** NOP singleton */ /** NOP singleton */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
FailableBiConsumer NOP = (t, u) -> {/* NOP */}; FailableBiConsumer NOP = (t, u) -> { /* NOP */ };
/** /**
* Returns The NOP singleton. * Returns The NOP singleton.

View File

@ -31,7 +31,7 @@ public interface FailableDoubleConsumer<E extends Throwable> {
/** NOP singleton */ /** NOP singleton */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
FailableDoubleConsumer NOP = t -> {/* NOP */}; FailableDoubleConsumer NOP = t -> { /* NOP */ };
/** /**
* Returns The NOP singleton. * Returns The NOP singleton.

View File

@ -31,7 +31,7 @@ public interface FailableIntConsumer<E extends Throwable> {
/** NOP singleton */ /** NOP singleton */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
FailableIntConsumer NOP = t -> {/* NOP */}; FailableIntConsumer NOP = t -> { /* NOP */ };
/** /**
* Returns The NOP singleton. * Returns The NOP singleton.

View File

@ -31,7 +31,7 @@ public interface FailableLongConsumer<E extends Throwable> {
/** NOP singleton */ /** NOP singleton */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
FailableLongConsumer NOP = t -> {/* NOP */}; FailableLongConsumer NOP = t -> { /* NOP */ };
/** /**
* Returns The NOP singleton. * Returns The NOP singleton.

View File

@ -31,7 +31,7 @@ public interface FailableObjDoubleConsumer<T, E extends Throwable> {
/** NOP singleton */ /** NOP singleton */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
FailableObjDoubleConsumer NOP = (t, u) -> {/* NOP */}; FailableObjDoubleConsumer NOP = (t, u) -> { /* NOP */ };
/** /**
* Returns The NOP singleton. * Returns The NOP singleton.

View File

@ -31,7 +31,7 @@ public interface FailableObjIntConsumer<T, E extends Throwable> {
/** NOP singleton */ /** NOP singleton */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
FailableObjIntConsumer NOP = (t, u) -> {/* NOP */}; FailableObjIntConsumer NOP = (t, u) -> { /* NOP */ };
/** /**
* Returns The NOP singleton. * Returns The NOP singleton.

View File

@ -31,7 +31,7 @@ public interface FailableObjLongConsumer<T, E extends Throwable> {
/** NOP singleton */ /** NOP singleton */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
FailableObjLongConsumer NOP = (t, u) -> {/* NOP */}; FailableObjLongConsumer NOP = (t, u) -> { /* NOP */ };
/** /**
* Returns The NOP singleton. * Returns The NOP singleton.

View File

@ -731,10 +731,10 @@ public final class Fraction extends Number implements Comparable<Fraction> {
if (numerator == 0) { if (numerator == 0) {
throw new ArithmeticException("Unable to invert zero."); throw new ArithmeticException("Unable to invert zero.");
} }
if (numerator==Integer.MIN_VALUE) { if (numerator == Integer.MIN_VALUE) {
throw new ArithmeticException("overflow: can't negate numerator"); throw new ArithmeticException("overflow: can't negate numerator");
} }
if (numerator<0) { if (numerator < 0) {
return new Fraction(-denominator, -numerator); return new Fraction(-denominator, -numerator);
} }
return new Fraction(denominator, numerator); return new Fraction(denominator, numerator);
@ -770,8 +770,7 @@ public final class Fraction extends Number implements Comparable<Fraction> {
// make sure we don't overflow unless the result *must* overflow. // make sure we don't overflow unless the result *must* overflow.
final int d1 = greatestCommonDivisor(numerator, fraction.denominator); final int d1 = greatestCommonDivisor(numerator, fraction.denominator);
final int d2 = greatestCommonDivisor(fraction.numerator, denominator); final int d2 = greatestCommonDivisor(fraction.numerator, denominator);
return getReducedFraction(mulAndCheck(numerator / d1, fraction.numerator / d2), return getReducedFraction(mulAndCheck(numerator / d1, fraction.numerator / d2), mulPosAndCheck(denominator / d2, fraction.denominator / d1));
mulPosAndCheck(denominator / d2, fraction.denominator / d1));
} }
/** /**
@ -783,7 +782,7 @@ public final class Fraction extends Number implements Comparable<Fraction> {
*/ */
public Fraction negate() { public Fraction negate() {
// the positive range is one smaller than the negative range of an int. // the positive range is one smaller than the negative range of an int.
if (numerator==Integer.MIN_VALUE) { if (numerator == Integer.MIN_VALUE) {
throw new ArithmeticException("overflow: too large to negate"); throw new ArithmeticException("overflow: too large to negate");
} }
return new Fraction(-numerator, denominator); return new Fraction(-numerator, denominator);
@ -875,7 +874,7 @@ public final class Fraction extends Number implements Comparable<Fraction> {
} else if ((numerator > 0 ? -numerator : numerator) < -denominator) { } else if ((numerator > 0 ? -numerator : numerator) < -denominator) {
// note that we do the magnitude comparison test above with // note that we do the magnitude comparison test above with
// NEGATIVE (not positive) numbers, since negative numbers // NEGATIVE (not positive) numbers, since negative numbers
// have a larger range. otherwise numerator==Integer.MIN_VALUE // have a larger range. otherwise numerator == Integer.MIN_VALUE
// is handled incorrectly. // is handled incorrectly.
final int properNumerator = getProperNumerator(); final int properNumerator = getProperNumerator();
if (properNumerator == 0) { if (properNumerator == 0) {

View File

@ -182,11 +182,11 @@ public class MutableDouble extends Number implements Comparable<MutableDouble>,
* also has the value {@code true}. However, there are two exceptions: * also has the value {@code true}. However, there are two exceptions:
* <ul> * <ul>
* <li>If {@code d1} and {@code d2} both represent {@code Double.NaN}, then the * <li>If {@code d1} and {@code d2} both represent {@code Double.NaN}, then the
* {@code equals} method returns {@code true}, even though {@code Double.NaN==Double.NaN} has * {@code equals} method returns {@code true}, even though {@code Double.NaN == Double.NaN} has
* the value {@code false}. * the value {@code false}.
* <li>If {@code d1} represents {@code +0.0} while {@code d2} represents {@code -0.0}, * <li>If {@code d1} represents {@code +0.0} while {@code d2} represents {@code -0.0},
* or vice versa, the {@code equal} test has the value {@code false}, even though * or vice versa, the {@code equal} test has the value {@code false}, even though
* {@code +0.0==-0.0} has the value {@code true}. This allows hashtables to operate properly. * {@code +0.0 == -0.0} has the value {@code true}. This allows hashtables to operate properly.
* </ul> * </ul>
* *
* @param obj the object to compare with, null returns false * @param obj the object to compare with, null returns false

View File

@ -182,11 +182,11 @@ public class MutableFloat extends Number implements Comparable<MutableFloat>, Mu
* also has the value {@code true}. However, there are two exceptions: * also has the value {@code true}. However, there are two exceptions:
* <ul> * <ul>
* <li>If {@code f1} and {@code f2} both represent {@code Float.NaN}, then the * <li>If {@code f1} and {@code f2} both represent {@code Float.NaN}, then the
* {@code equals} method returns {@code true}, even though {@code Float.NaN==Float.NaN} has * {@code equals} method returns {@code true}, even though {@code Float.NaN == Float.NaN} has
* the value {@code false}. * the value {@code false}.
* <li>If {@code f1} represents {@code +0.0f} while {@code f2} represents {@code -0.0f}, * <li>If {@code f1} represents {@code +0.0f} while {@code f2} represents {@code -0.0f},
* or vice versa, the {@code equal} test has the value {@code false}, even though * or vice versa, the {@code equal} test has the value {@code false}, even though
* {@code 0.0f==-0.0f} has the value {@code true}. * {@code 0.0f == -0.0f} has the value {@code true}.
* </ul> * </ul>
* This definition allows hashtables to operate properly. * This definition allows hashtables to operate properly.
* *

View File

@ -257,8 +257,7 @@ public class ConstructorUtils {
parameterTypes = ArrayUtils.nullToEmpty(parameterTypes); parameterTypes = ArrayUtils.nullToEmpty(parameterTypes);
final Constructor<T> ctor = getAccessibleConstructor(cls, parameterTypes); final Constructor<T> ctor = getAccessibleConstructor(cls, parameterTypes);
if (ctor == null) { if (ctor == null) {
throw new NoSuchMethodException( throw new NoSuchMethodException("No such accessible constructor on object: " + cls.getName());
"No such accessible constructor on object: "+ cls.getName());
} }
return ctor.newInstance(args); return ctor.newInstance(args);
} }

View File

@ -1713,7 +1713,7 @@ public class TypeUtils {
buf.insert(0, c.getSimpleName()).insert(0, '.'); buf.insert(0, c.getSimpleName()).insert(0, '.');
c = c.getEnclosingClass(); c = c.getEnclosingClass();
} }
} else if (d instanceof Type) {// not possible as of now } else if (d instanceof Type) { // not possible as of now
buf.append(toString((Type) d)); buf.append(toString((Type) d));
} else { } else {
buf.append(d); buf.append(d);

View File

@ -307,7 +307,6 @@ public class Streams {
* Performs a mutable reduction operation on the elements of this FailableStream. A mutable reduction is one in which * Performs a mutable reduction operation on the elements of this FailableStream. A mutable reduction is one in which
* the reduced value is a mutable result container, such as an {@link ArrayList}, and elements are incorporated by * the reduced value is a mutable result container, such as an {@link ArrayList}, and elements are incorporated by
* updating the state of the result rather than by replacing the result. This produces a result equivalent to: * updating the state of the result rather than by replacing the result. This produces a result equivalent to:
*
* <pre> * <pre>
* {@code * {@code
* R result = supplier.get(); * R result = supplier.get();
@ -316,29 +315,25 @@ public class Streams {
* return result; * return result;
* } * }
* </pre> * </pre>
*
* <p> * <p>
* Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations can be parallelized without requiring * Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations can be parallelized without requiring
* additional synchronization. * additional synchronization.
* </p> * </p>
*
* <p> * <p>
* This is a terminal operation. * This is a terminal operation.
* </p> * </p>
* * <p>
* Note There are many existing classes in the JDK whose signatures are well-suited for use with method references as * Note There are many existing classes in the JDK whose signatures are well-suited for use with method references as
* arguments to {@code collect()}. For example, the following will accumulate strings into an {@link ArrayList}: * arguments to {@code collect()}. For example, the following will accumulate strings into an {@link ArrayList}:
* * </p>
* <pre> * <pre>
* {@code * {@code
* List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll); * List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
* } * }
* </pre> * </pre>
*
* <p> * <p>
* The following will take a stream of strings and concatenates them into a single string: * The following will take a stream of strings and concatenates them into a single string:
* </p> * </p>
*
* <pre> * <pre>
* {@code * {@code
* String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString(); * String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
@ -362,7 +357,6 @@ public class Streams {
/** /**
* Returns a FailableStream consisting of the elements of this stream that match the given FailablePredicate. * Returns a FailableStream consisting of the elements of this stream that match the given FailablePredicate.
*
* <p> * <p>
* This is an intermediate operation. * This is an intermediate operation.
* </p> * </p>
@ -379,11 +373,9 @@ public class Streams {
/** /**
* Performs an action for each element of this stream. * Performs an action for each element of this stream.
*
* <p> * <p>
* This is a terminal operation. * This is a terminal operation.
* </p> * </p>
*
* <p> * <p>
* The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does * The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does
* <em>not</em> guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of * <em>not</em> guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of

View File

@ -413,7 +413,7 @@ public class EntityArrays {
*/ */
public static String[][] invert(final String[][] array) { public static String[][] invert(final String[][] array) {
final String[][] newarray = new String[array.length][2]; final String[][] newarray = new String[array.length][2];
for (int i = 0; i<array.length; i++) { for (int i = 0; i < array.length; i++) {
newarray[i][0] = array[i][1]; newarray[i][0] = array[i][1];
newarray[i][1] = array[i][0]; newarray[i][1] = array[i][0];
} }

View File

@ -310,7 +310,7 @@ public class DurationFormatUtils {
lastOutputSeconds = false; lastOutputSeconds = false;
} }
//as soon as we hit first nonliteral in optional, check for literal prefix //as soon as we hit first nonliteral in optional, check for literal prefix
if (inOptional && !isLiteral && !firstOptionalNonLiteral){ if (inOptional && !isLiteral && !firstOptionalNonLiteral) {
firstOptionalNonLiteral = true; firstOptionalNonLiteral = true;
if (lastOutputZero) { if (lastOutputZero) {
buffer.delete(optionalStart, buffer.length()); buffer.delete(optionalStart, buffer.length());
@ -680,14 +680,14 @@ public class DurationFormatUtils {
// TODO: Need to handle escaping of ' // TODO: Need to handle escaping of '
case '[': case '[':
if (inOptional) { if (inOptional) {
throw new IllegalArgumentException("Nested optional block at index: "+i); throw new IllegalArgumentException("Nested optional block at index: " + i);
} }
optionalIndex++; optionalIndex++;
inOptional = true; inOptional = true;
break; break;
case ']': case ']':
if (!inOptional) { if (!inOptional) {
throw new IllegalArgumentException("Attempting to close unopened optional block at index: "+i); throw new IllegalArgumentException("Attempting to close unopened optional block at index: " + i);
} }
inOptional = false; inOptional = false;
break; break;

View File

@ -218,11 +218,11 @@ public class FastDatePrinter implements DatePrinter, Serializable {
final int hours = offset / (60 * 60 * 1000); final int hours = offset / (60 * 60 * 1000);
appendDigits(buffer, hours); appendDigits(buffer, hours);
if (length<5) { if (length < 5) {
return; return;
} }
if (length==6) { if (length == 6) {
buffer.append(':'); buffer.append(':');
} }
@ -386,7 +386,7 @@ public class FastDatePrinter implements DatePrinter, Serializable {
@Override @Override
public int estimateLength() { public int estimateLength() {
int max = 0; int max = 0;
for (int i=values.length; --i >= 0; ) { for (int i = values.length; --i >= 0;) {
final int len = values[i].length(); final int len = values[i].length();
if (len > max) { if (len > max) {
max = len; max = len;

View File

@ -15,11 +15,9 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
--> -->
<!DOCTYPE module PUBLIC <!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd"> "https://checkstyle.org/dtds/configuration_1_3.dtd">
<!-- Apache Commons Lang customization of default Checkstyle behavior --> <!-- Apache Commons Lang customization of default Checkstyle behavior -->
<module name="Checker"> <module name="Checker">
<property name="localeLanguage" value="en"/> <property name="localeLanguage" value="en"/>
@ -53,6 +51,8 @@ limitations under the License.
<module name="RightCurly"/> <module name="RightCurly"/>
<module name="GenericWhitespace"/> <module name="GenericWhitespace"/>
<module name="WhitespaceAfter"/> <module name="WhitespaceAfter"/>
<module name="WhitespaceAround"/>
<module name="WhitespaceAroundCheck"/>
<module name="NoWhitespaceBefore"/> <module name="NoWhitespaceBefore"/>
<module name="ImportOrder"> <module name="ImportOrder">
<property name="option" value="top"/> <property name="option" value="top"/>

View File

@ -35,14 +35,14 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddFirstBoolean() { public void testAddFirstBoolean() {
boolean[] newArray; boolean[] newArray;
newArray = ArrayUtils.addFirst(null, false); newArray = ArrayUtils.addFirst(null, false);
assertArrayEquals(new boolean[]{false}, newArray); assertArrayEquals(new boolean[] { false }, newArray);
assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst(null, true); newArray = ArrayUtils.addFirst(null, true);
assertArrayEquals(new boolean[]{true}, newArray); assertArrayEquals(new boolean[] { true }, newArray);
assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
final boolean[] array1 = {true, false, true}; final boolean[] array1 = { true, false, true };
newArray = ArrayUtils.addFirst(array1, false); newArray = ArrayUtils.addFirst(array1, false);
assertArrayEquals(new boolean[]{false, true, false, true}, newArray); assertArrayEquals(new boolean[] { false, true, false, true }, newArray);
assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
} }
@ -50,17 +50,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddFirstByte() { public void testAddFirstByte() {
byte[] newArray; byte[] newArray;
newArray = ArrayUtils.addFirst((byte[]) null, (byte) 0); newArray = ArrayUtils.addFirst((byte[]) null, (byte) 0);
assertArrayEquals(new byte[]{0}, newArray); assertArrayEquals(new byte[] { 0 }, newArray);
assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst((byte[]) null, (byte) 1); newArray = ArrayUtils.addFirst((byte[]) null, (byte) 1);
assertArrayEquals(new byte[]{1}, newArray); assertArrayEquals(new byte[] { 1 }, newArray);
assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
final byte[] array1 = {1, 2, 3}; final byte[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.addFirst(array1, (byte) 0); newArray = ArrayUtils.addFirst(array1, (byte) 0);
assertArrayEquals(new byte[]{0, 1, 2, 3}, newArray); assertArrayEquals(new byte[] { 0, 1, 2, 3 }, newArray);
assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst(array1, (byte) 4); newArray = ArrayUtils.addFirst(array1, (byte) 4);
assertArrayEquals(new byte[]{4, 1, 2, 3}, newArray); assertArrayEquals(new byte[] { 4, 1, 2, 3 }, newArray);
assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
} }
@ -68,17 +68,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddFirstChar() { public void testAddFirstChar() {
char[] newArray; char[] newArray;
newArray = ArrayUtils.addFirst((char[]) null, (char) 0); newArray = ArrayUtils.addFirst((char[]) null, (char) 0);
assertArrayEquals(new char[]{0}, newArray); assertArrayEquals(new char[] { 0 }, newArray);
assertEquals(Character.TYPE, newArray.getClass().getComponentType()); assertEquals(Character.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst((char[]) null, (char) 1); newArray = ArrayUtils.addFirst((char[]) null, (char) 1);
assertArrayEquals(new char[]{1}, newArray); assertArrayEquals(new char[] { 1 }, newArray);
assertEquals(Character.TYPE, newArray.getClass().getComponentType()); assertEquals(Character.TYPE, newArray.getClass().getComponentType());
final char[] array1 = {1, 2, 3}; final char[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.addFirst(array1, (char) 0); newArray = ArrayUtils.addFirst(array1, (char) 0);
assertArrayEquals(new char[]{0, 1, 2, 3}, newArray); assertArrayEquals(new char[] { 0, 1, 2, 3 }, newArray);
assertEquals(Character.TYPE, newArray.getClass().getComponentType()); assertEquals(Character.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst(array1, (char) 4); newArray = ArrayUtils.addFirst(array1, (char) 4);
assertArrayEquals(new char[]{4, 1, 2, 3}, newArray); assertArrayEquals(new char[] { 4, 1, 2, 3 }, newArray);
assertEquals(Character.TYPE, newArray.getClass().getComponentType()); assertEquals(Character.TYPE, newArray.getClass().getComponentType());
} }
@ -86,17 +86,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddFirstDouble() { public void testAddFirstDouble() {
double[] newArray; double[] newArray;
newArray = ArrayUtils.addFirst((double[]) null, 0); newArray = ArrayUtils.addFirst((double[]) null, 0);
assertArrayEquals(new double[]{0}, newArray); assertArrayEquals(new double[] { 0 }, newArray);
assertEquals(Double.TYPE, newArray.getClass().getComponentType()); assertEquals(Double.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst((double[]) null, 1); newArray = ArrayUtils.addFirst((double[]) null, 1);
assertArrayEquals(new double[]{1}, newArray); assertArrayEquals(new double[] { 1 }, newArray);
assertEquals(Double.TYPE, newArray.getClass().getComponentType()); assertEquals(Double.TYPE, newArray.getClass().getComponentType());
final double[] array1 = {1, 2, 3}; final double[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.addFirst(array1, 0); newArray = ArrayUtils.addFirst(array1, 0);
assertArrayEquals(new double[]{0, 1, 2, 3}, newArray); assertArrayEquals(new double[] { 0, 1, 2, 3 }, newArray);
assertEquals(Double.TYPE, newArray.getClass().getComponentType()); assertEquals(Double.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst(array1, 4); newArray = ArrayUtils.addFirst(array1, 4);
assertArrayEquals(new double[]{4, 1, 2, 3}, newArray); assertArrayEquals(new double[] { 4, 1, 2, 3 }, newArray);
assertEquals(Double.TYPE, newArray.getClass().getComponentType()); assertEquals(Double.TYPE, newArray.getClass().getComponentType());
} }
@ -104,17 +104,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddFirstFloat() { public void testAddFirstFloat() {
float[] newArray; float[] newArray;
newArray = ArrayUtils.addFirst((float[]) null, 0); newArray = ArrayUtils.addFirst((float[]) null, 0);
assertArrayEquals(new float[]{0}, newArray); assertArrayEquals(new float[] { 0 }, newArray);
assertEquals(Float.TYPE, newArray.getClass().getComponentType()); assertEquals(Float.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst((float[]) null, 1); newArray = ArrayUtils.addFirst((float[]) null, 1);
assertArrayEquals(new float[]{1}, newArray); assertArrayEquals(new float[] { 1 }, newArray);
assertEquals(Float.TYPE, newArray.getClass().getComponentType()); assertEquals(Float.TYPE, newArray.getClass().getComponentType());
final float[] array1 = {1, 2, 3}; final float[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.addFirst(array1, 0); newArray = ArrayUtils.addFirst(array1, 0);
assertArrayEquals(new float[]{0, 1, 2, 3}, newArray); assertArrayEquals(new float[] { 0, 1, 2, 3 }, newArray);
assertEquals(Float.TYPE, newArray.getClass().getComponentType()); assertEquals(Float.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst(array1, 4); newArray = ArrayUtils.addFirst(array1, 4);
assertArrayEquals(new float[]{4, 1, 2, 3}, newArray); assertArrayEquals(new float[] { 4, 1, 2, 3 }, newArray);
assertEquals(Float.TYPE, newArray.getClass().getComponentType()); assertEquals(Float.TYPE, newArray.getClass().getComponentType());
} }
@ -122,17 +122,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddFirstInt() { public void testAddFirstInt() {
int[] newArray; int[] newArray;
newArray = ArrayUtils.addFirst((int[]) null, 0); newArray = ArrayUtils.addFirst((int[]) null, 0);
assertArrayEquals(new int[]{0}, newArray); assertArrayEquals(new int[] { 0 }, newArray);
assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst((int[]) null, 1); newArray = ArrayUtils.addFirst((int[]) null, 1);
assertArrayEquals(new int[]{1}, newArray); assertArrayEquals(new int[] { 1 }, newArray);
assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
final int[] array1 = {1, 2, 3}; final int[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.addFirst(array1, 0); newArray = ArrayUtils.addFirst(array1, 0);
assertArrayEquals(new int[]{0, 1, 2, 3}, newArray); assertArrayEquals(new int[] { 0, 1, 2, 3 }, newArray);
assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst(array1, 4); newArray = ArrayUtils.addFirst(array1, 4);
assertArrayEquals(new int[]{4, 1, 2, 3}, newArray); assertArrayEquals(new int[] { 4, 1, 2, 3 }, newArray);
assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
} }
@ -140,17 +140,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddFirstLong() { public void testAddFirstLong() {
long[] newArray; long[] newArray;
newArray = ArrayUtils.addFirst((long[]) null, 0); newArray = ArrayUtils.addFirst((long[]) null, 0);
assertArrayEquals(new long[]{0}, newArray); assertArrayEquals(new long[] { 0 }, newArray);
assertEquals(Long.TYPE, newArray.getClass().getComponentType()); assertEquals(Long.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst((long[]) null, 1); newArray = ArrayUtils.addFirst((long[]) null, 1);
assertArrayEquals(new long[]{1}, newArray); assertArrayEquals(new long[] { 1 }, newArray);
assertEquals(Long.TYPE, newArray.getClass().getComponentType()); assertEquals(Long.TYPE, newArray.getClass().getComponentType());
final long[] array1 = {1, 2, 3}; final long[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.addFirst(array1, 0); newArray = ArrayUtils.addFirst(array1, 0);
assertArrayEquals(new long[]{0, 1, 2, 3}, newArray); assertArrayEquals(new long[] { 0, 1, 2, 3 }, newArray);
assertEquals(Long.TYPE, newArray.getClass().getComponentType()); assertEquals(Long.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst(array1, 4); newArray = ArrayUtils.addFirst(array1, 4);
assertArrayEquals(new long[]{4, 1, 2, 3}, newArray); assertArrayEquals(new long[] { 4, 1, 2, 3 }, newArray);
assertEquals(Long.TYPE, newArray.getClass().getComponentType()); assertEquals(Long.TYPE, newArray.getClass().getComponentType());
} }
@ -158,16 +158,16 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddFirstObject() { public void testAddFirstObject() {
Object[] newArray; Object[] newArray;
//show that not casting is okay // show that not casting is okay
newArray = ArrayUtils.add((Object[]) null, "a"); newArray = ArrayUtils.add((Object[]) null, "a");
assertArrayEquals(new String[]{"a"}, newArray); assertArrayEquals(new String[] { "a" }, newArray);
assertArrayEquals(new Object[]{"a"}, newArray); assertArrayEquals(new Object[] { "a" }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
//show that not casting to Object[] is okay and will assume String based on "a" // show that not casting to Object[] is okay and will assume String based on "a"
final String[] newStringArray = ArrayUtils.add(null, "a"); final String[] newStringArray = ArrayUtils.add(null, "a");
assertArrayEquals(new String[]{"a"}, newStringArray); assertArrayEquals(new String[] { "a" }, newStringArray);
assertArrayEquals(new Object[]{"a"}, newStringArray); assertArrayEquals(new Object[] { "a" }, newStringArray);
assertEquals(String.class, newStringArray.getClass().getComponentType()); assertEquals(String.class, newStringArray.getClass().getComponentType());
final String[] stringArray1 = { "a", "b", "c" }; final String[] stringArray1 = { "a", "b", "c" };
@ -194,17 +194,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddFirstShort() { public void testAddFirstShort() {
short[] newArray; short[] newArray;
newArray = ArrayUtils.addFirst((short[]) null, (short) 0); newArray = ArrayUtils.addFirst((short[]) null, (short) 0);
assertArrayEquals(new short[]{0}, newArray); assertArrayEquals(new short[] { 0 }, newArray);
assertEquals(Short.TYPE, newArray.getClass().getComponentType()); assertEquals(Short.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst((short[]) null, (short) 1); newArray = ArrayUtils.addFirst((short[]) null, (short) 1);
assertArrayEquals(new short[]{1}, newArray); assertArrayEquals(new short[] { 1 }, newArray);
assertEquals(Short.TYPE, newArray.getClass().getComponentType()); assertEquals(Short.TYPE, newArray.getClass().getComponentType());
final short[] array1 = {1, 2, 3}; final short[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.addFirst(array1, (short) 0); newArray = ArrayUtils.addFirst(array1, (short) 0);
assertArrayEquals(new short[]{0, 1, 2, 3}, newArray); assertArrayEquals(new short[] { 0, 1, 2, 3 }, newArray);
assertEquals(Short.TYPE, newArray.getClass().getComponentType()); assertEquals(Short.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.addFirst(array1, (short) 4); newArray = ArrayUtils.addFirst(array1, (short) 4);
assertArrayEquals(new short[]{4, 1, 2, 3}, newArray); assertArrayEquals(new short[] { 4, 1, 2, 3 }, newArray);
assertEquals(Short.TYPE, newArray.getClass().getComponentType()); assertEquals(Short.TYPE, newArray.getClass().getComponentType());
} }
@ -212,14 +212,14 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectArrayBoolean() { public void testAddObjectArrayBoolean() {
boolean[] newArray; boolean[] newArray;
newArray = ArrayUtils.add(null, false); newArray = ArrayUtils.add(null, false);
assertArrayEquals(new boolean[]{false}, newArray); assertArrayEquals(new boolean[] { false }, newArray);
assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(null, true); newArray = ArrayUtils.add(null, true);
assertArrayEquals(new boolean[]{true}, newArray); assertArrayEquals(new boolean[] { true }, newArray);
assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
final boolean[] array1 = {true, false, true}; final boolean[] array1 = { true, false, true };
newArray = ArrayUtils.add(array1, false); newArray = ArrayUtils.add(array1, false);
assertArrayEquals(new boolean[]{true, false, true, false}, newArray); assertArrayEquals(new boolean[] { true, false, true, false }, newArray);
assertEquals(Boolean.TYPE, newArray.getClass().getComponentType()); assertEquals(Boolean.TYPE, newArray.getClass().getComponentType());
} }
@ -227,17 +227,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectArrayByte() { public void testAddObjectArrayByte() {
byte[] newArray; byte[] newArray;
newArray = ArrayUtils.add((byte[]) null, (byte) 0); newArray = ArrayUtils.add((byte[]) null, (byte) 0);
assertArrayEquals(new byte[]{0}, newArray); assertArrayEquals(new byte[] { 0 }, newArray);
assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((byte[]) null, (byte) 1); newArray = ArrayUtils.add((byte[]) null, (byte) 1);
assertArrayEquals(new byte[]{1}, newArray); assertArrayEquals(new byte[] { 1 }, newArray);
assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
final byte[] array1 = {1, 2, 3}; final byte[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.add(array1, (byte) 0); newArray = ArrayUtils.add(array1, (byte) 0);
assertArrayEquals(new byte[]{1, 2, 3, 0}, newArray); assertArrayEquals(new byte[] { 1, 2, 3, 0 }, newArray);
assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, (byte) 4); newArray = ArrayUtils.add(array1, (byte) 4);
assertArrayEquals(new byte[]{1, 2, 3, 4}, newArray); assertArrayEquals(new byte[] { 1, 2, 3, 4 }, newArray);
assertEquals(Byte.TYPE, newArray.getClass().getComponentType()); assertEquals(Byte.TYPE, newArray.getClass().getComponentType());
} }
@ -245,17 +245,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectArrayChar() { public void testAddObjectArrayChar() {
char[] newArray; char[] newArray;
newArray = ArrayUtils.add((char[]) null, (char) 0); newArray = ArrayUtils.add((char[]) null, (char) 0);
assertArrayEquals(new char[]{0}, newArray); assertArrayEquals(new char[] { 0 }, newArray);
assertEquals(Character.TYPE, newArray.getClass().getComponentType()); assertEquals(Character.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((char[]) null, (char) 1); newArray = ArrayUtils.add((char[]) null, (char) 1);
assertArrayEquals(new char[]{1}, newArray); assertArrayEquals(new char[] { 1 }, newArray);
assertEquals(Character.TYPE, newArray.getClass().getComponentType()); assertEquals(Character.TYPE, newArray.getClass().getComponentType());
final char[] array1 = {1, 2, 3}; final char[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.add(array1, (char) 0); newArray = ArrayUtils.add(array1, (char) 0);
assertArrayEquals(new char[]{1, 2, 3, 0}, newArray); assertArrayEquals(new char[] { 1, 2, 3, 0 }, newArray);
assertEquals(Character.TYPE, newArray.getClass().getComponentType()); assertEquals(Character.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, (char) 4); newArray = ArrayUtils.add(array1, (char) 4);
assertArrayEquals(new char[]{1, 2, 3, 4}, newArray); assertArrayEquals(new char[] { 1, 2, 3, 4 }, newArray);
assertEquals(Character.TYPE, newArray.getClass().getComponentType()); assertEquals(Character.TYPE, newArray.getClass().getComponentType());
} }
@ -263,17 +263,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectArrayDouble() { public void testAddObjectArrayDouble() {
double[] newArray; double[] newArray;
newArray = ArrayUtils.add((double[]) null, 0); newArray = ArrayUtils.add((double[]) null, 0);
assertArrayEquals(new double[]{0}, newArray); assertArrayEquals(new double[] { 0 }, newArray);
assertEquals(Double.TYPE, newArray.getClass().getComponentType()); assertEquals(Double.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((double[]) null, 1); newArray = ArrayUtils.add((double[]) null, 1);
assertArrayEquals(new double[]{1}, newArray); assertArrayEquals(new double[] { 1 }, newArray);
assertEquals(Double.TYPE, newArray.getClass().getComponentType()); assertEquals(Double.TYPE, newArray.getClass().getComponentType());
final double[] array1 = {1, 2, 3}; final double[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.add(array1, 0); newArray = ArrayUtils.add(array1, 0);
assertArrayEquals(new double[]{1, 2, 3, 0}, newArray); assertArrayEquals(new double[] { 1, 2, 3, 0 }, newArray);
assertEquals(Double.TYPE, newArray.getClass().getComponentType()); assertEquals(Double.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, 4); newArray = ArrayUtils.add(array1, 4);
assertArrayEquals(new double[]{1, 2, 3, 4}, newArray); assertArrayEquals(new double[] { 1, 2, 3, 4 }, newArray);
assertEquals(Double.TYPE, newArray.getClass().getComponentType()); assertEquals(Double.TYPE, newArray.getClass().getComponentType());
} }
@ -281,17 +281,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectArrayFloat() { public void testAddObjectArrayFloat() {
float[] newArray; float[] newArray;
newArray = ArrayUtils.add((float[]) null, 0); newArray = ArrayUtils.add((float[]) null, 0);
assertArrayEquals(new float[]{0}, newArray); assertArrayEquals(new float[] { 0 }, newArray);
assertEquals(Float.TYPE, newArray.getClass().getComponentType()); assertEquals(Float.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((float[]) null, 1); newArray = ArrayUtils.add((float[]) null, 1);
assertArrayEquals(new float[]{1}, newArray); assertArrayEquals(new float[] { 1 }, newArray);
assertEquals(Float.TYPE, newArray.getClass().getComponentType()); assertEquals(Float.TYPE, newArray.getClass().getComponentType());
final float[] array1 = {1, 2, 3}; final float[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.add(array1, 0); newArray = ArrayUtils.add(array1, 0);
assertArrayEquals(new float[]{1, 2, 3, 0}, newArray); assertArrayEquals(new float[] { 1, 2, 3, 0 }, newArray);
assertEquals(Float.TYPE, newArray.getClass().getComponentType()); assertEquals(Float.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, 4); newArray = ArrayUtils.add(array1, 4);
assertArrayEquals(new float[]{1, 2, 3, 4}, newArray); assertArrayEquals(new float[] { 1, 2, 3, 4 }, newArray);
assertEquals(Float.TYPE, newArray.getClass().getComponentType()); assertEquals(Float.TYPE, newArray.getClass().getComponentType());
} }
@ -299,17 +299,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectArrayInt() { public void testAddObjectArrayInt() {
int[] newArray; int[] newArray;
newArray = ArrayUtils.add((int[]) null, 0); newArray = ArrayUtils.add((int[]) null, 0);
assertArrayEquals(new int[]{0}, newArray); assertArrayEquals(new int[] { 0 }, newArray);
assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((int[]) null, 1); newArray = ArrayUtils.add((int[]) null, 1);
assertArrayEquals(new int[]{1}, newArray); assertArrayEquals(new int[] { 1 }, newArray);
assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
final int[] array1 = {1, 2, 3}; final int[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.add(array1, 0); newArray = ArrayUtils.add(array1, 0);
assertArrayEquals(new int[]{1, 2, 3, 0}, newArray); assertArrayEquals(new int[] { 1, 2, 3, 0 }, newArray);
assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, 4); newArray = ArrayUtils.add(array1, 4);
assertArrayEquals(new int[]{1, 2, 3, 4}, newArray); assertArrayEquals(new int[] { 1, 2, 3, 4 }, newArray);
assertEquals(Integer.TYPE, newArray.getClass().getComponentType()); assertEquals(Integer.TYPE, newArray.getClass().getComponentType());
} }
@ -317,17 +317,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectArrayLong() { public void testAddObjectArrayLong() {
long[] newArray; long[] newArray;
newArray = ArrayUtils.add((long[]) null, 0); newArray = ArrayUtils.add((long[]) null, 0);
assertArrayEquals(new long[]{0}, newArray); assertArrayEquals(new long[] { 0 }, newArray);
assertEquals(Long.TYPE, newArray.getClass().getComponentType()); assertEquals(Long.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((long[]) null, 1); newArray = ArrayUtils.add((long[]) null, 1);
assertArrayEquals(new long[]{1}, newArray); assertArrayEquals(new long[] { 1 }, newArray);
assertEquals(Long.TYPE, newArray.getClass().getComponentType()); assertEquals(Long.TYPE, newArray.getClass().getComponentType());
final long[] array1 = {1, 2, 3}; final long[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.add(array1, 0); newArray = ArrayUtils.add(array1, 0);
assertArrayEquals(new long[]{1, 2, 3, 0}, newArray); assertArrayEquals(new long[] { 1, 2, 3, 0 }, newArray);
assertEquals(Long.TYPE, newArray.getClass().getComponentType()); assertEquals(Long.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, 4); newArray = ArrayUtils.add(array1, 4);
assertArrayEquals(new long[]{1, 2, 3, 4}, newArray); assertArrayEquals(new long[] { 1, 2, 3, 4 }, newArray);
assertEquals(Long.TYPE, newArray.getClass().getComponentType()); assertEquals(Long.TYPE, newArray.getClass().getComponentType());
} }
@ -335,35 +335,35 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectArrayObject() { public void testAddObjectArrayObject() {
Object[] newArray; Object[] newArray;
//show that not casting is okay // show that not casting is okay
newArray = ArrayUtils.add((Object[]) null, "a"); newArray = ArrayUtils.add((Object[]) null, "a");
assertArrayEquals(new String[]{"a"}, newArray); assertArrayEquals(new String[] { "a" }, newArray);
assertArrayEquals(new Object[]{"a"}, newArray); assertArrayEquals(new Object[] { "a" }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
//show that not casting to Object[] is okay and will assume String based on "a" // show that not casting to Object[] is okay and will assume String based on "a"
final String[] newStringArray = ArrayUtils.add(null, "a"); final String[] newStringArray = ArrayUtils.add(null, "a");
assertArrayEquals(new String[]{"a"}, newStringArray); assertArrayEquals(new String[] { "a" }, newStringArray);
assertArrayEquals(new Object[]{"a"}, newStringArray); assertArrayEquals(new Object[] { "a" }, newStringArray);
assertEquals(String.class, newStringArray.getClass().getComponentType()); assertEquals(String.class, newStringArray.getClass().getComponentType());
final String[] stringArray1 = {"a", "b", "c"}; final String[] stringArray1 = { "a", "b", "c" };
newArray = ArrayUtils.add(stringArray1, null); newArray = ArrayUtils.add(stringArray1, null);
assertArrayEquals(new String[]{"a", "b", "c", null}, newArray); assertArrayEquals(new String[] { "a", "b", "c", null }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(stringArray1, "d"); newArray = ArrayUtils.add(stringArray1, "d");
assertArrayEquals(new String[]{"a", "b", "c", "d"}, newArray); assertArrayEquals(new String[] { "a", "b", "c", "d" }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
Number[] numberArray1 = {Integer.valueOf(1), Double.valueOf(2)}; Number[] numberArray1 = { Integer.valueOf(1), Double.valueOf(2) };
newArray = ArrayUtils.add(numberArray1, Float.valueOf(3)); newArray = ArrayUtils.add(numberArray1, Float.valueOf(3));
assertArrayEquals(new Number[]{Integer.valueOf(1), Double.valueOf(2), Float.valueOf(3)}, newArray); assertArrayEquals(new Number[] { Integer.valueOf(1), Double.valueOf(2), Float.valueOf(3) }, newArray);
assertEquals(Number.class, newArray.getClass().getComponentType()); assertEquals(Number.class, newArray.getClass().getComponentType());
numberArray1 = null; numberArray1 = null;
newArray = ArrayUtils.add(numberArray1, Float.valueOf(3)); newArray = ArrayUtils.add(numberArray1, Float.valueOf(3));
assertArrayEquals(new Float[]{Float.valueOf(3)}, newArray); assertArrayEquals(new Float[] { Float.valueOf(3) }, newArray);
assertEquals(Float.class, newArray.getClass().getComponentType()); assertEquals(Float.class, newArray.getClass().getComponentType());
} }
@ -371,17 +371,17 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectArrayShort() { public void testAddObjectArrayShort() {
short[] newArray; short[] newArray;
newArray = ArrayUtils.add((short[]) null, (short) 0); newArray = ArrayUtils.add((short[]) null, (short) 0);
assertArrayEquals(new short[]{0}, newArray); assertArrayEquals(new short[] { 0 }, newArray);
assertEquals(Short.TYPE, newArray.getClass().getComponentType()); assertEquals(Short.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add((short[]) null, (short) 1); newArray = ArrayUtils.add((short[]) null, (short) 1);
assertArrayEquals(new short[]{1}, newArray); assertArrayEquals(new short[] { 1 }, newArray);
assertEquals(Short.TYPE, newArray.getClass().getComponentType()); assertEquals(Short.TYPE, newArray.getClass().getComponentType());
final short[] array1 = {1, 2, 3}; final short[] array1 = { 1, 2, 3 };
newArray = ArrayUtils.add(array1, (short) 0); newArray = ArrayUtils.add(array1, (short) 0);
assertArrayEquals(new short[]{1, 2, 3, 0}, newArray); assertArrayEquals(new short[] { 1, 2, 3, 0 }, newArray);
assertEquals(Short.TYPE, newArray.getClass().getComponentType()); assertEquals(Short.TYPE, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(array1, (short) 4); newArray = ArrayUtils.add(array1, (short) 4);
assertArrayEquals(new short[]{1, 2, 3, 4}, newArray); assertArrayEquals(new short[] { 1, 2, 3, 4 }, newArray);
assertEquals(Short.TYPE, newArray.getClass().getComponentType()); assertEquals(Short.TYPE, newArray.getClass().getComponentType());
} }
@ -389,93 +389,94 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectArrayToObjectArray() { public void testAddObjectArrayToObjectArray() {
assertNull(ArrayUtils.addAll(null, (Object[]) null)); assertNull(ArrayUtils.addAll(null, (Object[]) null));
Object[] newArray; Object[] newArray;
final String[] stringArray1 = {"a", "b", "c"}; final String[] stringArray1 = { "a", "b", "c" };
final String[] stringArray2 = {"1", "2", "3"}; final String[] stringArray2 = { "1", "2", "3" };
newArray = ArrayUtils.addAll(stringArray1, (String[]) null); newArray = ArrayUtils.addAll(stringArray1, (String[]) null);
assertNotSame(stringArray1, newArray); assertNotSame(stringArray1, newArray);
assertArrayEquals(stringArray1, newArray); assertArrayEquals(stringArray1, newArray);
assertArrayEquals(new String[]{"a", "b", "c"}, newArray); assertArrayEquals(new String[] { "a", "b", "c" }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.addAll(null, stringArray2); newArray = ArrayUtils.addAll(null, stringArray2);
assertNotSame(stringArray2, newArray); assertNotSame(stringArray2, newArray);
assertArrayEquals(stringArray2, newArray); assertArrayEquals(stringArray2, newArray);
assertArrayEquals(new String[]{"1", "2", "3"}, newArray); assertArrayEquals(new String[] { "1", "2", "3" }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.addAll(stringArray1, stringArray2); newArray = ArrayUtils.addAll(stringArray1, stringArray2);
assertArrayEquals(new String[]{"a", "b", "c", "1", "2", "3"}, newArray); assertArrayEquals(new String[] { "a", "b", "c", "1", "2", "3" }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, (String[]) null); newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, (String[]) null);
assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, newArray); assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, newArray);
assertArrayEquals(new String[]{}, newArray); assertArrayEquals(new String[] {}, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.addAll(null, ArrayUtils.EMPTY_STRING_ARRAY); newArray = ArrayUtils.addAll(null, ArrayUtils.EMPTY_STRING_ARRAY);
assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, newArray); assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, newArray);
assertArrayEquals(new String[]{}, newArray); assertArrayEquals(new String[] {}, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY); newArray = ArrayUtils.addAll(ArrayUtils.EMPTY_STRING_ARRAY, ArrayUtils.EMPTY_STRING_ARRAY);
assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, newArray); assertArrayEquals(ArrayUtils.EMPTY_STRING_ARRAY, newArray);
assertArrayEquals(new String[]{}, newArray); assertArrayEquals(new String[] {}, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
final String[] stringArrayNull = {null}; final String[] stringArrayNull = { null };
newArray = ArrayUtils.addAll(stringArrayNull, stringArrayNull); newArray = ArrayUtils.addAll(stringArrayNull, stringArrayNull);
assertArrayEquals(new String[]{null, null}, newArray); assertArrayEquals(new String[] { null, null }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
// boolean // boolean
assertArrayEquals(new boolean[]{true, false, false, true}, ArrayUtils.addAll(new boolean[]{true, false}, false, true)); assertArrayEquals(new boolean[] { true, false, false, true }, ArrayUtils.addAll(new boolean[] { true, false }, false, true));
assertArrayEquals(new boolean[]{false, true}, ArrayUtils.addAll(null, new boolean[]{false, true})); assertArrayEquals(new boolean[] { false, true }, ArrayUtils.addAll(null, new boolean[] { false, true }));
assertArrayEquals(new boolean[]{true, false}, ArrayUtils.addAll(new boolean[]{true, false}, null)); assertArrayEquals(new boolean[] { true, false }, ArrayUtils.addAll(new boolean[] { true, false }, null));
// char // char
assertArrayEquals(new char[]{'a', 'b', 'c', 'd'}, ArrayUtils.addAll(new char[]{'a', 'b'}, 'c', 'd')); assertArrayEquals(new char[] { 'a', 'b', 'c', 'd' }, ArrayUtils.addAll(new char[] { 'a', 'b' }, 'c', 'd'));
assertArrayEquals(new char[]{'c', 'd'}, ArrayUtils.addAll(null, new char[]{'c', 'd'})); assertArrayEquals(new char[] { 'c', 'd' }, ArrayUtils.addAll(null, new char[] { 'c', 'd' }));
assertArrayEquals(new char[]{'a', 'b'}, ArrayUtils.addAll(new char[]{'a', 'b'}, null)); assertArrayEquals(new char[] { 'a', 'b' }, ArrayUtils.addAll(new char[] { 'a', 'b' }, null));
// byte // byte
assertArrayEquals(new byte[]{(byte) 0, (byte) 1, (byte) 2, (byte) 3}, ArrayUtils.addAll(new byte[]{(byte) 0, (byte) 1}, (byte) 2, (byte) 3)); assertArrayEquals(new byte[] { (byte) 0, (byte) 1, (byte) 2, (byte) 3 }, ArrayUtils.addAll(new byte[] { (byte) 0, (byte) 1 }, (byte) 2, (byte) 3));
assertArrayEquals(new byte[]{(byte) 2, (byte) 3}, ArrayUtils.addAll(null, new byte[]{(byte) 2, (byte) 3})); assertArrayEquals(new byte[] { (byte) 2, (byte) 3 }, ArrayUtils.addAll(null, new byte[] { (byte) 2, (byte) 3 }));
assertArrayEquals(new byte[]{(byte) 0, (byte) 1}, ArrayUtils.addAll(new byte[]{(byte) 0, (byte) 1}, null)); assertArrayEquals(new byte[] { (byte) 0, (byte) 1 }, ArrayUtils.addAll(new byte[] { (byte) 0, (byte) 1 }, null));
// short // short
assertArrayEquals(new short[]{(short) 10, (short) 20, (short) 30, (short) 40}, ArrayUtils.addAll(new short[]{(short) 10, (short) 20}, (short) 30, (short) 40)); assertArrayEquals(new short[] { (short) 10, (short) 20, (short) 30, (short) 40 },
ArrayUtils.addAll(new short[] { (short) 10, (short) 20 }, (short) 30, (short) 40));
assertArrayEquals(new short[]{(short) 30, (short) 40}, ArrayUtils.addAll(null, new short[]{(short) 30, (short) 40})); assertArrayEquals(new short[] { (short) 30, (short) 40 }, ArrayUtils.addAll(null, new short[] { (short) 30, (short) 40 }));
assertArrayEquals(new short[]{(short) 10, (short) 20}, ArrayUtils.addAll(new short[]{(short) 10, (short) 20}, null)); assertArrayEquals(new short[] { (short) 10, (short) 20 }, ArrayUtils.addAll(new short[] { (short) 10, (short) 20 }, null));
// int // int
assertArrayEquals(new int[]{1, 1000, -1000, -1}, ArrayUtils.addAll(new int[]{1, 1000}, -1000, -1)); assertArrayEquals(new int[] { 1, 1000, -1000, -1 }, ArrayUtils.addAll(new int[] { 1, 1000 }, -1000, -1));
assertArrayEquals(new int[]{-1000, -1}, ArrayUtils.addAll(null, new int[]{-1000, -1})); assertArrayEquals(new int[] { -1000, -1 }, ArrayUtils.addAll(null, new int[] { -1000, -1 }));
assertArrayEquals(new int[]{1, 1000}, ArrayUtils.addAll(new int[]{1, 1000}, null)); assertArrayEquals(new int[] { 1, 1000 }, ArrayUtils.addAll(new int[] { 1, 1000 }, null));
// long // long
assertArrayEquals(new long[]{1L, -1L, 1000L, -1000L}, ArrayUtils.addAll(new long[]{1L, -1L}, 1000L, -1000L)); assertArrayEquals(new long[] { 1L, -1L, 1000L, -1000L }, ArrayUtils.addAll(new long[] { 1L, -1L }, 1000L, -1000L));
assertArrayEquals(new long[]{1000L, -1000L}, ArrayUtils.addAll(null, new long[]{1000L, -1000L})); assertArrayEquals(new long[] { 1000L, -1000L }, ArrayUtils.addAll(null, new long[] { 1000L, -1000L }));
assertArrayEquals(new long[]{1L, -1L}, ArrayUtils.addAll(new long[]{1L, -1L}, null)); assertArrayEquals(new long[] { 1L, -1L }, ArrayUtils.addAll(new long[] { 1L, -1L }, null));
// float // float
assertArrayEquals(new float[]{10.5f, 10.1f, 1.6f, 0.01f}, ArrayUtils.addAll(new float[]{10.5f, 10.1f}, 1.6f, 0.01f)); assertArrayEquals(new float[] { 10.5f, 10.1f, 1.6f, 0.01f }, ArrayUtils.addAll(new float[] { 10.5f, 10.1f }, 1.6f, 0.01f));
assertArrayEquals(new float[]{1.6f, 0.01f}, ArrayUtils.addAll(null, new float[]{1.6f, 0.01f})); assertArrayEquals(new float[] { 1.6f, 0.01f }, ArrayUtils.addAll(null, new float[] { 1.6f, 0.01f }));
assertArrayEquals(new float[]{10.5f, 10.1f}, ArrayUtils.addAll(new float[]{10.5f, 10.1f}, null)); assertArrayEquals(new float[] { 10.5f, 10.1f }, ArrayUtils.addAll(new float[] { 10.5f, 10.1f }, null));
// double // double
assertArrayEquals(new double[]{Math.PI, -Math.PI, 0, 9.99}, ArrayUtils.addAll(new double[]{Math.PI, -Math.PI}, 0, 9.99)); assertArrayEquals(new double[] { Math.PI, -Math.PI, 0, 9.99 }, ArrayUtils.addAll(new double[] { Math.PI, -Math.PI }, 0, 9.99));
assertArrayEquals(new double[]{0, 9.99}, ArrayUtils.addAll(null, new double[]{0, 9.99})); assertArrayEquals(new double[] { 0, 9.99 }, ArrayUtils.addAll(null, new double[] { 0, 9.99 }));
assertArrayEquals(new double[]{Math.PI, -Math.PI}, ArrayUtils.addAll(new double[]{Math.PI, -Math.PI}, null)); assertArrayEquals(new double[] { Math.PI, -Math.PI }, ArrayUtils.addAll(new double[] { Math.PI, -Math.PI }, null));
} }
@ -484,25 +485,25 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testAddObjectAtIndex() { public void testAddObjectAtIndex() {
Object[] newArray; Object[] newArray;
newArray = ArrayUtils.add((Object[]) null, 0, "a"); newArray = ArrayUtils.add((Object[]) null, 0, "a");
assertArrayEquals(new String[]{"a"}, newArray); assertArrayEquals(new String[] { "a" }, newArray);
assertArrayEquals(new Object[]{"a"}, newArray); assertArrayEquals(new Object[] { "a" }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
final String[] stringArray1 = {"a", "b", "c"}; final String[] stringArray1 = { "a", "b", "c" };
newArray = ArrayUtils.add(stringArray1, 0, null); newArray = ArrayUtils.add(stringArray1, 0, null);
assertArrayEquals(new String[]{null, "a", "b", "c"}, newArray); assertArrayEquals(new String[] { null, "a", "b", "c" }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(stringArray1, 1, null); newArray = ArrayUtils.add(stringArray1, 1, null);
assertArrayEquals(new String[]{"a", null, "b", "c"}, newArray); assertArrayEquals(new String[] { "a", null, "b", "c" }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(stringArray1, 3, null); newArray = ArrayUtils.add(stringArray1, 3, null);
assertArrayEquals(new String[]{"a", "b", "c", null}, newArray); assertArrayEquals(new String[] { "a", "b", "c", null }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
newArray = ArrayUtils.add(stringArray1, 3, "d"); newArray = ArrayUtils.add(stringArray1, 3, "d");
assertArrayEquals(new String[]{"a", "b", "c", "d"}, newArray); assertArrayEquals(new String[] { "a", "b", "c", "d" }, newArray);
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
assertEquals(String.class, newArray.getClass().getComponentType()); assertEquals(String.class, newArray.getClass().getComponentType());
final Object[] o = {"1", "2", "4"}; final Object[] o = { "1", "2", "4" };
final Object[] result = ArrayUtils.add(o, 2, "3"); final Object[] result = ArrayUtils.add(o, 2, "3");
final Object[] result2 = ArrayUtils.add(o, 3, "5"); final Object[] result2 = ArrayUtils.add(o, 3, "5");
@ -520,134 +521,133 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
assertEquals("5", result2[3]); assertEquals("5", result2[3]);
// boolean tests // boolean tests
boolean[] booleanArray = ArrayUtils.add( null, 0, true ); boolean[] booleanArray = ArrayUtils.add(null, 0, true);
assertArrayEquals(new boolean[]{true}, booleanArray); assertArrayEquals(new boolean[] { true }, booleanArray);
IndexOutOfBoundsException e = IndexOutOfBoundsException e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(null, -1, true));
assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( null, -1, true));
assertEquals("Index: -1, Length: 0", e.getMessage()); assertEquals("Index: -1, Length: 0", e.getMessage());
booleanArray = ArrayUtils.add( new boolean[] { true }, 0, false); booleanArray = ArrayUtils.add(new boolean[] { true }, 0, false);
assertArrayEquals(new boolean[]{false, true}, booleanArray); assertArrayEquals(new boolean[] { false, true }, booleanArray);
booleanArray = ArrayUtils.add( new boolean[] { false }, 1, true); booleanArray = ArrayUtils.add(new boolean[] { false }, 1, true);
assertArrayEquals(new boolean[]{false, true}, booleanArray); assertArrayEquals(new boolean[] { false, true }, booleanArray);
booleanArray = ArrayUtils.add( new boolean[] { true, false }, 1, true); booleanArray = ArrayUtils.add(new boolean[] { true, false }, 1, true);
assertArrayEquals(new boolean[]{true, true, false}, booleanArray); assertArrayEquals(new boolean[] { true, true, false }, booleanArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new boolean[] { true, false }, 4, true)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new boolean[] { true, false }, 4, true));
assertEquals("Index: 4, Length: 2", e.getMessage()); assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new boolean[] { true, false }, -1, true)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new boolean[] { true, false }, -1, true));
assertEquals("Index: -1, Length: 2", e.getMessage()); assertEquals("Index: -1, Length: 2", e.getMessage());
// char tests // char tests
char[] charArray = ArrayUtils.add( (char[]) null, 0, 'a' ); char[] charArray = ArrayUtils.add((char[]) null, 0, 'a');
assertArrayEquals(new char[]{'a'}, charArray); assertArrayEquals(new char[] { 'a' }, charArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (char[]) null, -1, 'a' )); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add((char[]) null, -1, 'a'));
assertEquals("Index: -1, Length: 0", e.getMessage()); assertEquals("Index: -1, Length: 0", e.getMessage());
charArray = ArrayUtils.add( new char[] { 'a' }, 0, 'b'); charArray = ArrayUtils.add(new char[] { 'a' }, 0, 'b');
assertArrayEquals(new char[]{'b', 'a'}, charArray); assertArrayEquals(new char[] { 'b', 'a' }, charArray);
charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 0, 'c'); charArray = ArrayUtils.add(new char[] { 'a', 'b' }, 0, 'c');
assertArrayEquals(new char[]{'c', 'a', 'b'}, charArray); assertArrayEquals(new char[] { 'c', 'a', 'b' }, charArray);
charArray = ArrayUtils.add( new char[] { 'a', 'b' }, 1, 'k'); charArray = ArrayUtils.add(new char[] { 'a', 'b' }, 1, 'k');
assertArrayEquals(new char[]{'a', 'k', 'b'}, charArray); assertArrayEquals(new char[] { 'a', 'k', 'b' }, charArray);
charArray = ArrayUtils.add( new char[] { 'a', 'b', 'c' }, 1, 't'); charArray = ArrayUtils.add(new char[] { 'a', 'b', 'c' }, 1, 't');
assertArrayEquals(new char[]{'a', 't', 'b', 'c'}, charArray); assertArrayEquals(new char[] { 'a', 't', 'b', 'c' }, charArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new char[] { 'a', 'b' }, 4, 'c')); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new char[] { 'a', 'b' }, 4, 'c'));
assertEquals("Index: 4, Length: 2", e.getMessage()); assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new char[] { 'a', 'b' }, -1, 'c')); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new char[] { 'a', 'b' }, -1, 'c'));
assertEquals("Index: -1, Length: 2", e.getMessage()); assertEquals("Index: -1, Length: 2", e.getMessage());
// short tests // short tests
short[] shortArray = ArrayUtils.add( new short[] { 1 }, 0, (short) 2); short[] shortArray = ArrayUtils.add(new short[] { 1 }, 0, (short) 2);
assertArrayEquals(new short[]{2, 1}, shortArray); assertArrayEquals(new short[] { 2, 1 }, shortArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (short[]) null, -1, (short) 2)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add((short[]) null, -1, (short) 2));
assertEquals("Index: -1, Length: 0", e.getMessage()); assertEquals("Index: -1, Length: 0", e.getMessage());
shortArray = ArrayUtils.add( new short[] { 2, 6 }, 2, (short) 10); shortArray = ArrayUtils.add(new short[] { 2, 6 }, 2, (short) 10);
assertArrayEquals(new short[]{2, 6, 10}, shortArray); assertArrayEquals(new short[] { 2, 6, 10 }, shortArray);
shortArray = ArrayUtils.add( new short[] { 2, 6 }, 0, (short) -4); shortArray = ArrayUtils.add(new short[] { 2, 6 }, 0, (short) -4);
assertArrayEquals(new short[]{-4, 2, 6}, shortArray); assertArrayEquals(new short[] { -4, 2, 6 }, shortArray);
shortArray = ArrayUtils.add( new short[] { 2, 6, 3 }, 2, (short) 1); shortArray = ArrayUtils.add(new short[] { 2, 6, 3 }, 2, (short) 1);
assertArrayEquals(new short[]{2, 6, 1, 3}, shortArray); assertArrayEquals(new short[] { 2, 6, 1, 3 }, shortArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new short[] { 2, 6 }, 4, (short) 10)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new short[] { 2, 6 }, 4, (short) 10));
assertEquals("Index: 4, Length: 2", e.getMessage()); assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new short[] { 2, 6 }, -1, (short) 10)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new short[] { 2, 6 }, -1, (short) 10));
assertEquals("Index: -1, Length: 2", e.getMessage()); assertEquals("Index: -1, Length: 2", e.getMessage());
// byte tests // byte tests
byte[] byteArray = ArrayUtils.add( new byte[] { 1 }, 0, (byte) 2); byte[] byteArray = ArrayUtils.add(new byte[] { 1 }, 0, (byte) 2);
assertArrayEquals(new byte[]{2, 1}, byteArray); assertArrayEquals(new byte[] { 2, 1 }, byteArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (byte[]) null, -1, (byte) 2)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add((byte[]) null, -1, (byte) 2));
assertEquals("Index: -1, Length: 0", e.getMessage()); assertEquals("Index: -1, Length: 0", e.getMessage());
byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 2, (byte) 3); byteArray = ArrayUtils.add(new byte[] { 2, 6 }, 2, (byte) 3);
assertArrayEquals(new byte[]{2, 6, 3}, byteArray); assertArrayEquals(new byte[] { 2, 6, 3 }, byteArray);
byteArray = ArrayUtils.add( new byte[] { 2, 6 }, 0, (byte) 1); byteArray = ArrayUtils.add(new byte[] { 2, 6 }, 0, (byte) 1);
assertArrayEquals(new byte[]{1, 2, 6}, byteArray); assertArrayEquals(new byte[] { 1, 2, 6 }, byteArray);
byteArray = ArrayUtils.add( new byte[] { 2, 6, 3 }, 2, (byte) 1); byteArray = ArrayUtils.add(new byte[] { 2, 6, 3 }, 2, (byte) 1);
assertArrayEquals(new byte[]{2, 6, 1, 3}, byteArray); assertArrayEquals(new byte[] { 2, 6, 1, 3 }, byteArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new byte[] { 2, 6 }, 4, (byte) 3)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new byte[] { 2, 6 }, 4, (byte) 3));
assertEquals("Index: 4, Length: 2", e.getMessage()); assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new byte[] { 2, 6 }, -1, (byte) 3)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new byte[] { 2, 6 }, -1, (byte) 3));
assertEquals("Index: -1, Length: 2", e.getMessage()); assertEquals("Index: -1, Length: 2", e.getMessage());
// int tests // int tests
int[] intArray = ArrayUtils.add( new int[] { 1 }, 0, 2); int[] intArray = ArrayUtils.add(new int[] { 1 }, 0, 2);
assertArrayEquals(new int[]{2, 1}, intArray); assertArrayEquals(new int[] { 2, 1 }, intArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (int[]) null, -1, 2)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add((int[]) null, -1, 2));
assertEquals("Index: -1, Length: 0", e.getMessage()); assertEquals("Index: -1, Length: 0", e.getMessage());
intArray = ArrayUtils.add( new int[] { 2, 6 }, 2, 10); intArray = ArrayUtils.add(new int[] { 2, 6 }, 2, 10);
assertArrayEquals(new int[]{2, 6, 10}, intArray); assertArrayEquals(new int[] { 2, 6, 10 }, intArray);
intArray = ArrayUtils.add( new int[] { 2, 6 }, 0, -4); intArray = ArrayUtils.add(new int[] { 2, 6 }, 0, -4);
assertArrayEquals(new int[]{-4, 2, 6}, intArray); assertArrayEquals(new int[] { -4, 2, 6 }, intArray);
intArray = ArrayUtils.add( new int[] { 2, 6, 3 }, 2, 1); intArray = ArrayUtils.add(new int[] { 2, 6, 3 }, 2, 1);
assertArrayEquals(new int[]{2, 6, 1, 3}, intArray); assertArrayEquals(new int[] { 2, 6, 1, 3 }, intArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new int[] { 2, 6 }, 4, 10)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new int[] { 2, 6 }, 4, 10));
assertEquals("Index: 4, Length: 2", e.getMessage()); assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new int[] { 2, 6 }, -1, 10)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new int[] { 2, 6 }, -1, 10));
assertEquals("Index: -1, Length: 2", e.getMessage()); assertEquals("Index: -1, Length: 2", e.getMessage());
// long tests // long tests
long[] longArray = ArrayUtils.add( new long[] { 1L }, 0, 2L); long[] longArray = ArrayUtils.add(new long[] { 1L }, 0, 2L);
assertArrayEquals(new long[]{2L, 1L}, longArray); assertArrayEquals(new long[] { 2L, 1L }, longArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (long[]) null, -1, 2L)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add((long[]) null, -1, 2L));
assertEquals("Index: -1, Length: 0", e.getMessage()); assertEquals("Index: -1, Length: 0", e.getMessage());
longArray = ArrayUtils.add( new long[] { 2L, 6L }, 2, 10L); longArray = ArrayUtils.add(new long[] { 2L, 6L }, 2, 10L);
assertArrayEquals(new long[]{2L, 6L, 10L}, longArray); assertArrayEquals(new long[] { 2L, 6L, 10L }, longArray);
longArray = ArrayUtils.add( new long[] { 2L, 6L }, 0, -4L); longArray = ArrayUtils.add(new long[] { 2L, 6L }, 0, -4L);
assertArrayEquals(new long[]{-4L, 2L, 6L}, longArray); assertArrayEquals(new long[] { -4L, 2L, 6L }, longArray);
longArray = ArrayUtils.add( new long[] { 2L, 6L, 3L }, 2, 1L); longArray = ArrayUtils.add(new long[] { 2L, 6L, 3L }, 2, 1L);
assertArrayEquals(new long[]{2L, 6L, 1L, 3L}, longArray); assertArrayEquals(new long[] { 2L, 6L, 1L, 3L }, longArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new long[] { 2L, 6L }, 4, 10L)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new long[] { 2L, 6L }, 4, 10L));
assertEquals("Index: 4, Length: 2", e.getMessage()); assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new long[] { 2L, 6L }, -1, 10L)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new long[] { 2L, 6L }, -1, 10L));
assertEquals("Index: -1, Length: 2", e.getMessage()); assertEquals("Index: -1, Length: 2", e.getMessage());
// float tests // float tests
float[] floatArray = ArrayUtils.add( new float[] { 1.1f }, 0, 2.2f); float[] floatArray = ArrayUtils.add(new float[] { 1.1f }, 0, 2.2f);
assertArrayEquals(new float[]{2.2f, 1.1f}, floatArray); assertArrayEquals(new float[] { 2.2f, 1.1f }, floatArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( (float[]) null, -1, 2.2f)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add((float[]) null, -1, 2.2f));
assertEquals("Index: -1, Length: 0", e.getMessage()); assertEquals("Index: -1, Length: 0", e.getMessage());
floatArray = ArrayUtils.add( new float[] { 2.3f, 6.4f }, 2, 10.5f); floatArray = ArrayUtils.add(new float[] { 2.3f, 6.4f }, 2, 10.5f);
assertArrayEquals(new float[]{2.3f, 6.4f, 10.5f}, floatArray); assertArrayEquals(new float[] { 2.3f, 6.4f, 10.5f }, floatArray);
floatArray = ArrayUtils.add( new float[] { 2.6f, 6.7f }, 0, -4.8f); floatArray = ArrayUtils.add(new float[] { 2.6f, 6.7f }, 0, -4.8f);
assertArrayEquals(new float[]{-4.8f, 2.6f, 6.7f}, floatArray); assertArrayEquals(new float[] { -4.8f, 2.6f, 6.7f }, floatArray);
floatArray = ArrayUtils.add( new float[] { 2.9f, 6.0f, 0.3f }, 2, 1.0f); floatArray = ArrayUtils.add(new float[] { 2.9f, 6.0f, 0.3f }, 2, 1.0f);
assertArrayEquals(new float[]{2.9f, 6.0f, 1.0f, 0.3f}, floatArray); assertArrayEquals(new float[] { 2.9f, 6.0f, 1.0f, 0.3f }, floatArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new float[] { 2.3f, 6.4f }, 4, 10.5f)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new float[] { 2.3f, 6.4f }, 4, 10.5f));
assertEquals("Index: 4, Length: 2", e.getMessage()); assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new float[] { 2.3f, 6.4f }, -1, 10.5f)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new float[] { 2.3f, 6.4f }, -1, 10.5f));
assertEquals("Index: -1, Length: 2", e.getMessage()); assertEquals("Index: -1, Length: 2", e.getMessage());
// double tests // double tests
double[] doubleArray = ArrayUtils.add( new double[] { 1.1 }, 0, 2.2); double[] doubleArray = ArrayUtils.add(new double[] { 1.1 }, 0, 2.2);
assertArrayEquals(new double[]{2.2, 1.1}, doubleArray); assertArrayEquals(new double[] { 2.2, 1.1 }, doubleArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(null, -1, 2.2)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(null, -1, 2.2));
assertEquals("Index: -1, Length: 0", e.getMessage()); assertEquals("Index: -1, Length: 0", e.getMessage());
doubleArray = ArrayUtils.add( new double[] { 2.3, 6.4 }, 2, 10.5); doubleArray = ArrayUtils.add(new double[] { 2.3, 6.4 }, 2, 10.5);
assertArrayEquals(new double[]{2.3, 6.4, 10.5}, doubleArray); assertArrayEquals(new double[] { 2.3, 6.4, 10.5 }, doubleArray);
doubleArray = ArrayUtils.add( new double[] { 2.6, 6.7 }, 0, -4.8); doubleArray = ArrayUtils.add(new double[] { 2.6, 6.7 }, 0, -4.8);
assertArrayEquals(new double[]{-4.8, 2.6, 6.7}, doubleArray); assertArrayEquals(new double[] { -4.8, 2.6, 6.7 }, doubleArray);
doubleArray = ArrayUtils.add( new double[] { 2.9, 6.0, 0.3 }, 2, 1.0); doubleArray = ArrayUtils.add(new double[] { 2.9, 6.0, 0.3 }, 2, 1.0);
assertArrayEquals(new double[]{2.9, 6.0, 1.0, 0.3}, doubleArray); assertArrayEquals(new double[] { 2.9, 6.0, 1.0, 0.3 }, doubleArray);
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new double[] { 2.3, 6.4 }, 4, 10.5)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new double[] { 2.3, 6.4 }, 4, 10.5));
assertEquals("Index: 4, Length: 2", e.getMessage()); assertEquals("Index: 4, Length: 2", e.getMessage());
e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add( new double[] { 2.3, 6.4 }, -1, 10.5)); e = assertThrows(IndexOutOfBoundsException.class, () -> ArrayUtils.add(new double[] { 2.3, 6.4 }, -1, 10.5));
assertEquals("Index: -1, Length: 2", e.getMessage()); assertEquals("Index: -1, Length: 2", e.getMessage());
} }
@ -655,19 +655,18 @@ public class ArrayUtilsAddTest extends AbstractLangTest {
public void testJira567() { public void testJira567() {
final Number[] n; final Number[] n;
// Valid array construction // Valid array construction
n = ArrayUtils.addAll(new Number[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)}); n = ArrayUtils.addAll(new Number[] { Integer.valueOf(1) }, new Long[] { Long.valueOf(2) });
assertEquals(2, n.length); assertEquals(2, n.length);
assertEquals(Number.class, n.getClass().getComponentType()); assertEquals(Number.class, n.getClass().getComponentType());
// Invalid - can't store Long in Integer array // Invalid - can't store Long in Integer array
assertThrows(IllegalArgumentException.class, assertThrows(IllegalArgumentException.class, () -> ArrayUtils.addAll(new Integer[] { Integer.valueOf(1) }, new Long[] { Long.valueOf(2) }));
() -> ArrayUtils.addAll(new Integer[]{Integer.valueOf(1)}, new Long[]{Long.valueOf(2)}));
} }
@Test @Test
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public void testLANG571() { public void testLANG571() {
final String[] stringArray=null; final String[] stringArray = null;
final String aString=null; final String aString = null;
assertThrows(IllegalArgumentException.class, () -> ArrayUtils.add(stringArray, aString)); assertThrows(IllegalArgumentException.class, () -> ArrayUtils.add(stringArray, aString));
assertThrows(IllegalArgumentException.class, () -> ArrayUtils.add(stringArray, 0, aString)); assertThrows(IllegalArgumentException.class, () -> ArrayUtils.add(stringArray, 0, aString));
} }

View File

@ -5501,37 +5501,31 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSubarrChar() { public void testSubarrChar() {
final char[] nullArray = null; final char[] nullArray = null;
final char[] array = {'a', 'b', 'c', 'd', 'e', 'f'}; final char[] array = { 'a', 'b', 'c', 'd', 'e', 'f' };
final char[] leftSubarray = {'a', 'b', 'c', 'd'}; final char[] leftSubarray = { 'a', 'b', 'c', 'd' };
final char[] midSubarray = {'b', 'c', 'd', 'e'}; final char[] midSubarray = { 'b', 'c', 'd', 'e' };
final char[] rightSubarray = {'c', 'd', 'e', 'f'}; final char[] rightSubarray = { 'c', 'd', 'e', 'f' };
assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end"); assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, 0, 4)), "0 start, mid end");
assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end"); assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, 0, array.length)), "0 start, length end");
assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end"); assertTrue(ArrayUtils.isEquals(midSubarray, ArrayUtils.subarray(array, 1, 5)), "mid start, mid end");
assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, array.length)), "mid start, length end");
"mid start, length end");
assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input"); assertNull(ArrayUtils.subarray(nullArray, 0, 3), "null input");
assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2), assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2), "empty array");
"empty array");
assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end"); assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 2), "start > end");
assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end"); assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end");
assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), assertTrue(ArrayUtils.isEquals(leftSubarray, ArrayUtils.subarray(array, -2, 4)), "start undershoot, normal end");
"start undershoot, normal end");
assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end"); assertEquals(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 33, 4), "start overshoot, any end");
assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), assertTrue(ArrayUtils.isEquals(rightSubarray, ArrayUtils.subarray(array, 2, 33)), "normal start, end overshoot");
"normal start, end overshoot");
assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot"); assertTrue(ArrayUtils.isEquals(array, ArrayUtils.subarray(array, -2, 12)), "start undershoot, end overshoot");
// empty-return tests // empty-return tests
assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2), assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(ArrayUtils.EMPTY_CHAR_ARRAY, 1, 2), "empty array, object test");
"empty array, object test");
assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test"); assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 4, 1), "start > end, object test");
assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test"); assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 3, 3), "start == end, object test");
assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 8733, 4), assertSame(ArrayUtils.EMPTY_CHAR_ARRAY, ArrayUtils.subarray(array, 8733, 4), "start overshoot, any end, object test");
"start overshoot, any end, object test");
// array type tests // array type tests
@ -5540,7 +5534,7 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapBoolean() { public void testSwapBoolean() {
final boolean[] array = {true, false, false}; final boolean[] array = { true, false, false };
ArrayUtils.swap(array, 0, 2); ArrayUtils.swap(array, 0, 2);
assertFalse(array[0]); assertFalse(array[0]);
assertFalse(array[1]); assertFalse(array[1]);
@ -5549,38 +5543,38 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapBooleanRange() { public void testSwapBooleanRange() {
boolean[] array = {false, false, true, true}; boolean[] array = { false, false, true, true };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertTrue(array[0]); assertTrue(array[0]);
assertTrue(array[1]); assertTrue(array[1]);
assertFalse(array[2]); assertFalse(array[2]);
assertFalse(array[3]); assertFalse(array[3]);
array = new boolean[]{false, true, false}; array = new boolean[] { false, true, false };
ArrayUtils.swap(array, 0, 3); ArrayUtils.swap(array, 0, 3);
assertFalse(array[0]); assertFalse(array[0]);
assertTrue(array[1]); assertTrue(array[1]);
assertFalse(array[2]); assertFalse(array[2]);
array = new boolean[]{true, true, false}; array = new boolean[] { true, true, false };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertFalse(array[0]); assertFalse(array[0]);
assertTrue(array[1]); assertTrue(array[1]);
assertTrue(array[2]); assertTrue(array[2]);
array = new boolean[]{true, true, false}; array = new boolean[] { true, true, false };
ArrayUtils.swap(array, -1, 2, 2); ArrayUtils.swap(array, -1, 2, 2);
assertFalse(array[0]); assertFalse(array[0]);
assertTrue(array[1]); assertTrue(array[1]);
assertTrue(array[2]); assertTrue(array[2]);
array = new boolean[]{true, true, false}; array = new boolean[] { true, true, false };
ArrayUtils.swap(array, 0, -1, 2); ArrayUtils.swap(array, 0, -1, 2);
assertTrue(array[0]); assertTrue(array[0]);
assertTrue(array[1]); assertTrue(array[1]);
assertFalse(array[2]); assertFalse(array[2]);
array = new boolean[]{true, true, false}; array = new boolean[] { true, true, false };
ArrayUtils.swap(array, -1, -1, 2); ArrayUtils.swap(array, -1, -1, 2);
assertTrue(array[0]); assertTrue(array[0]);
assertTrue(array[1]); assertTrue(array[1]);
@ -5589,7 +5583,7 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapByte() { public void testSwapByte() {
final byte[] array = {1, 2, 3}; final byte[] array = { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2); ArrayUtils.swap(array, 0, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -5598,38 +5592,38 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapByteRange() { public void testSwapByteRange() {
byte[] array = {1, 2, 3, 4}; byte[] array = { 1, 2, 3, 4 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(4, array[1]); assertEquals(4, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
assertEquals(2, array[3]); assertEquals(2, array[3]);
array = new byte[]{1, 2, 3}; array = new byte[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 3); ArrayUtils.swap(array, 0, 3);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new byte[]{1, 2, 3}; array = new byte[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new byte[]{1, 2, 3}; array = new byte[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, 2, 2); ArrayUtils.swap(array, -1, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new byte[]{1, 2, 3}; array = new byte[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, -1, 2); ArrayUtils.swap(array, 0, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new byte[]{1, 2, 3}; array = new byte[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, -1, 2); ArrayUtils.swap(array, -1, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -5638,53 +5632,53 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapChar() { public void testSwapChar() {
char[] array = {1, 2, 3}; char[] array = { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2); ArrayUtils.swap(array, 0, 2);
assertArrayEquals(new char[]{3, 2, 1}, array); assertArrayEquals(new char[] { 3, 2, 1 }, array);
array = new char[]{1, 2, 3}; array = new char[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 0); ArrayUtils.swap(array, 0, 0);
assertArrayEquals(new char[]{1, 2, 3}, array); assertArrayEquals(new char[] { 1, 2, 3 }, array);
array = new char[]{1, 2, 3}; array = new char[] { 1, 2, 3 };
ArrayUtils.swap(array, 1, 0); ArrayUtils.swap(array, 1, 0);
assertArrayEquals(new char[]{2, 1, 3}, array); assertArrayEquals(new char[] { 2, 1, 3 }, array);
} }
@Test @Test
public void testSwapCharRange() { public void testSwapCharRange() {
char[] array = {1, 2, 3, 4}; char[] array = { 1, 2, 3, 4 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(4, array[1]); assertEquals(4, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
assertEquals(2, array[3]); assertEquals(2, array[3]);
array = new char[]{1, 2, 3}; array = new char[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 3); ArrayUtils.swap(array, 0, 3);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new char[]{1, 2, 3}; array = new char[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new char[]{1, 2, 3}; array = new char[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, 2, 2); ArrayUtils.swap(array, -1, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new char[]{1, 2, 3}; array = new char[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, -1, 2); ArrayUtils.swap(array, 0, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new char[]{1, 2, 3}; array = new char[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, -1, 2); ArrayUtils.swap(array, -1, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -5693,7 +5687,7 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapDouble() { public void testSwapDouble() {
final double[] array = {1, 2, 3}; final double[] array = { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2); ArrayUtils.swap(array, 0, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -5702,38 +5696,38 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapDoubleRange() { public void testSwapDoubleRange() {
double[] array = {1, 2, 3, 4}; double[] array = { 1, 2, 3, 4 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(4, array[1]); assertEquals(4, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
assertEquals(2, array[3]); assertEquals(2, array[3]);
array = new double[]{1, 2, 3}; array = new double[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 3); ArrayUtils.swap(array, 0, 3);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new double[]{1, 2, 3}; array = new double[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new double[]{1, 2, 3}; array = new double[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, 2, 2); ArrayUtils.swap(array, -1, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new double[]{1, 2, 3}; array = new double[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, -1, 2); ArrayUtils.swap(array, 0, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new double[]{1, 2, 3}; array = new double[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, -1, 2); ArrayUtils.swap(array, -1, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -5805,7 +5799,7 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapFloat() { public void testSwapFloat() {
final float[] array = {1, 2, 3}; final float[] array = { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2); ArrayUtils.swap(array, 0, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -5814,38 +5808,38 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapFloatRange() { public void testSwapFloatRange() {
float[] array = {1, 2, 3, 4}; float[] array = { 1, 2, 3, 4 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(4, array[1]); assertEquals(4, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
assertEquals(2, array[3]); assertEquals(2, array[3]);
array = new float[]{1, 2, 3}; array = new float[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 3); ArrayUtils.swap(array, 0, 3);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new float[]{1, 2, 3}; array = new float[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new float[]{1, 2, 3}; array = new float[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, 2, 2); ArrayUtils.swap(array, -1, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new float[]{1, 2, 3}; array = new float[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, -1, 2); ArrayUtils.swap(array, 0, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new float[]{1, 2, 3}; array = new float[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, -1, 2); ArrayUtils.swap(array, -1, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -5854,7 +5848,7 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapInt() { public void testSwapInt() {
final int[] array = {1, 2, 3}; final int[] array = { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2); ArrayUtils.swap(array, 0, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -5864,49 +5858,49 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapIntExchangedOffsets() { public void testSwapIntExchangedOffsets() {
int[] array; int[] array;
array = new int[]{1, 2, 3}; array = new int[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 1, 2); ArrayUtils.swap(array, 0, 1, 2);
assertArrayEquals(new int[]{2, 3, 1}, array); assertArrayEquals(new int[] { 2, 3, 1 }, array);
array = new int[]{1, 2, 3}; array = new int[] { 1, 2, 3 };
ArrayUtils.swap(array, 1, 0, 2); ArrayUtils.swap(array, 1, 0, 2);
assertArrayEquals(new int[]{2, 3, 1}, array); assertArrayEquals(new int[] { 2, 3, 1 }, array);
} }
@Test @Test
public void testSwapIntRange() { public void testSwapIntRange() {
int[] array = {1, 2, 3, 4}; int[] array = { 1, 2, 3, 4 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(4, array[1]); assertEquals(4, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
assertEquals(2, array[3]); assertEquals(2, array[3]);
array = new int[]{1, 2, 3}; array = new int[] { 1, 2, 3 };
ArrayUtils.swap(array, 3, 0); ArrayUtils.swap(array, 3, 0);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new int[]{1, 2, 3}; array = new int[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new int[]{1, 2, 3}; array = new int[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, 2, 2); ArrayUtils.swap(array, -1, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new int[]{1, 2, 3}; array = new int[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, -1, 2); ArrayUtils.swap(array, 0, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new int[]{1, 2, 3}; array = new int[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, -1, 2); ArrayUtils.swap(array, -1, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -5915,7 +5909,7 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapLong() { public void testSwapLong() {
final long[] array = {1, 2, 3}; final long[] array = { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2); ArrayUtils.swap(array, 0, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -5924,38 +5918,38 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapLongRange() { public void testSwapLongRange() {
long[] array = {1, 2, 3, 4}; long[] array = { 1, 2, 3, 4 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(4, array[1]); assertEquals(4, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
assertEquals(2, array[3]); assertEquals(2, array[3]);
array = new long[]{1, 2, 3}; array = new long[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 3); ArrayUtils.swap(array, 0, 3);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new long[]{1, 2, 3}; array = new long[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new long[]{1, 2, 3}; array = new long[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, 2, 2); ArrayUtils.swap(array, -1, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new long[]{1, 2, 3}; array = new long[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, -1, 2); ArrayUtils.swap(array, 0, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new long[]{1, 2, 3}; array = new long[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, -1, 2); ArrayUtils.swap(array, -1, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -6027,7 +6021,7 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapObject() { public void testSwapObject() {
final String[] array = {"1", "2", "3"}; final String[] array = { "1", "2", "3" };
ArrayUtils.swap(array, 0, 2); ArrayUtils.swap(array, 0, 2);
assertEquals("3", array[0]); assertEquals("3", array[0]);
assertEquals("2", array[1]); assertEquals("2", array[1]);
@ -6036,21 +6030,21 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapObjectRange() { public void testSwapObjectRange() {
String[] array = {"1", "2", "3", "4"}; String[] array = { "1", "2", "3", "4" };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals("3", array[0]); assertEquals("3", array[0]);
assertEquals("4", array[1]); assertEquals("4", array[1]);
assertEquals("1", array[2]); assertEquals("1", array[2]);
assertEquals("2", array[3]); assertEquals("2", array[3]);
array = new String[]{"1", "2", "3", "4"}; array = new String[] { "1", "2", "3", "4" };
ArrayUtils.swap(array, -1, 2, 3); ArrayUtils.swap(array, -1, 2, 3);
assertEquals("3", array[0]); assertEquals("3", array[0]);
assertEquals("4", array[1]); assertEquals("4", array[1]);
assertEquals("1", array[2]); assertEquals("1", array[2]);
assertEquals("2", array[3]); assertEquals("2", array[3]);
array = new String[]{"1", "2", "3", "4", "5"}; array = new String[] { "1", "2", "3", "4", "5" };
ArrayUtils.swap(array, -3, 2, 3); ArrayUtils.swap(array, -3, 2, 3);
assertEquals("3", array[0]); assertEquals("3", array[0]);
assertEquals("4", array[1]); assertEquals("4", array[1]);
@ -6058,7 +6052,7 @@ public class ArrayUtilsTest extends AbstractLangTest {
assertEquals("2", array[3]); assertEquals("2", array[3]);
assertEquals("1", array[4]); assertEquals("1", array[4]);
array = new String[]{"1", "2", "3", "4", "5"}; array = new String[] { "1", "2", "3", "4", "5" };
ArrayUtils.swap(array, 2, -2, 3); ArrayUtils.swap(array, 2, -2, 3);
assertEquals("3", array[0]); assertEquals("3", array[0]);
assertEquals("4", array[1]); assertEquals("4", array[1]);
@ -6077,7 +6071,7 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapShort() { public void testSwapShort() {
final short[] array = {1, 2, 3}; final short[] array = { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2); ArrayUtils.swap(array, 0, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -6086,38 +6080,38 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testSwapShortRange() { public void testSwapShortRange() {
short[] array = {1, 2, 3, 4}; short[] array = { 1, 2, 3, 4 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(4, array[1]); assertEquals(4, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
assertEquals(2, array[3]); assertEquals(2, array[3]);
array = new short[]{1, 2, 3}; array = new short[] { 1, 2, 3 };
ArrayUtils.swap(array, 3, 0); ArrayUtils.swap(array, 3, 0);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new short[]{1, 2, 3}; array = new short[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, 2, 2); ArrayUtils.swap(array, 0, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new short[]{1, 2, 3}; array = new short[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, 2, 2); ArrayUtils.swap(array, -1, 2, 2);
assertEquals(3, array[0]); assertEquals(3, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(1, array[2]); assertEquals(1, array[2]);
array = new short[]{1, 2, 3}; array = new short[] { 1, 2, 3 };
ArrayUtils.swap(array, 0, -1, 2); ArrayUtils.swap(array, 0, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
assertEquals(3, array[2]); assertEquals(3, array[2]);
array = new short[]{1, 2, 3}; array = new short[] { 1, 2, 3 };
ArrayUtils.swap(array, -1, -1, 2); ArrayUtils.swap(array, -1, -1, 2);
assertEquals(1, array[0]); assertEquals(1, array[0]);
assertEquals(2, array[1]); assertEquals(2, array[1]);
@ -6130,7 +6124,7 @@ public class ArrayUtilsTest extends AbstractLangTest {
final BitSet emptySet = new BitSet(); final BitSet emptySet = new BitSet();
final BitSet testSet = new BitSet(); final BitSet testSet = new BitSet();
assertEquals(emptySet, ArrayUtils.indexesOf(array, 0)); assertEquals(emptySet, ArrayUtils.indexesOf(array, 0));
array = new int[]{0, 1, 2, 3, 0}; array = new int[] { 0, 1, 2, 3, 0 };
testSet.set(0); testSet.set(0);
testSet.set(4); testSet.set(4);
assertEquals(testSet, ArrayUtils.indexesOf(array, 0)); assertEquals(testSet, ArrayUtils.indexesOf(array, 0));
@ -6148,20 +6142,17 @@ public class ArrayUtilsTest extends AbstractLangTest {
@Test @Test
public void testToMap() { public void testToMap() {
Map<?, ?> map = ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"hello", "world"}}); Map<?, ?> map = ArrayUtils.toMap(new String[][] { { "foo", "bar" }, { "hello", "world" } });
assertEquals("bar", map.get("foo")); assertEquals("bar", map.get("foo"));
assertEquals("world", map.get("hello")); assertEquals("world", map.get("hello"));
assertNull(ArrayUtils.toMap(null)); assertNull(ArrayUtils.toMap(null));
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () -> ArrayUtils.toMap(new String[][] { { "foo", "bar" }, { "short" } }));
ArrayUtils.toMap(new String[][]{{"foo", "bar"}, {"short"}})); assertThrows(IllegalArgumentException.class, () -> ArrayUtils.toMap(new Object[] { new Object[] { "foo", "bar" }, "illegal type" }));
assertThrows(IllegalArgumentException.class, () -> assertThrows(IllegalArgumentException.class, () -> ArrayUtils.toMap(new Object[] { new Object[] { "foo", "bar" }, null }));
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>() { map = ArrayUtils.toMap(new Object[] { new Map.Entry<Object, Object>() {
@Override @Override
public boolean equals(final Object o) { public boolean equals(final Object o) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
@ -6186,18 +6177,18 @@ public class ArrayUtilsTest extends AbstractLangTest {
public Object setValue(final Object value) { public Object setValue(final Object value) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
}}); } });
assertEquals("bar", map.get("foo")); assertEquals("bar", map.get("foo"));
// Return empty map when got input array with length = 0 // Return empty map when got input array with length = 0
assertEquals(Collections.emptyMap(), ArrayUtils.toMap(new Object[0])); assertEquals(Collections.emptyMap(), ArrayUtils.toMap(new Object[0]));
// Test all null values // Test all null values
map = ArrayUtils.toMap(new Object[][] { {null, null}, {null, null} }); map = ArrayUtils.toMap(new Object[][] { { null, null }, { null, null } });
assertEquals(Collections.singletonMap(null, null), map); assertEquals(Collections.singletonMap(null, null), map);
// Test duplicate keys // Test duplicate keys
map = ArrayUtils.toMap(new Object[][] { {"key", "value2"}, {"key", "value1"} }); map = ArrayUtils.toMap(new Object[][] { { "key", "value2" }, { "key", "value1" } });
assertEquals(Collections.singletonMap("key", "value1"), map); assertEquals(Collections.singletonMap("key", "value1"), map);
} }

View File

@ -56,7 +56,7 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
} }
static class TestData{ static class TestData {
final String source; final String source;
final boolean ignoreCase; final boolean ignoreCase;
final int toffset; final int toffset;
@ -65,8 +65,9 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
final int len; final int len;
final boolean expected; final boolean expected;
final Class<? extends Throwable> 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) { 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; this.source = source;
this.ignoreCase = ignoreCase; this.ignoreCase = ignoreCase;
this.toffset = toffset; this.toffset = toffset;
@ -76,8 +77,9 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
this.expected = expected; this.expected = expected;
this.throwable = null; this.throwable = null;
} }
TestData(final String source, final boolean ignoreCase, final int toffset,
final String other, final int ooffset, final int len, 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 Class<? extends Throwable> throwable) {
this.source = source; this.source = source;
this.ignoreCase = ignoreCase; this.ignoreCase = ignoreCase;
this.toffset = toffset; this.toffset = toffset;
@ -87,11 +89,12 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
this.expected = false; this.expected = false;
this.throwable = throwable; this.throwable = throwable;
} }
@Override @Override
public String toString() { public String toString() {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
sb.append(source).append("[").append(toffset).append("]"); sb.append(source).append("[").append(toffset).append("]");
sb.append(ignoreCase? " caseblind ":" samecase "); sb.append(ignoreCase ? " caseblind " : " samecase ");
sb.append(other).append("[").append(ooffset).append("]"); sb.append(other).append("[").append(ooffset).append("]");
sb.append(" ").append(len).append(" => "); sb.append(" ").append(len).append(" => ");
if (throwable != null) { if (throwable != null) {
@ -142,23 +145,26 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
} }
private static final TestData[] TEST_DATA = { private static final TestData[] TEST_DATA = {
// Source IgnoreCase Offset Other Offset Length Result // @formatter:off
new TestData("", true, -1, "", -1, -1, false), // Source IgnoreCase Offset Other Offset Length Result
new TestData("", true, 0, "", 0, 1, false), new TestData("", true, -1, "", -1, -1, false),
new TestData("a", true, 0, "abc", 0, 0, true), new TestData("", true, 0, "", 0, 1, false),
new TestData("a", true, 0, "abc", 0, 1, true), new TestData("a", true, 0, "abc", 0, 0, true),
new TestData("a", true, 0, null, 0, 0, NullPointerException.class), new TestData("a", true, 0, "abc", 0, 1, true),
new TestData(null, true, 0, null, 0, 0, NullPointerException.class), new TestData("a", true, 0, null, 0, 0, NullPointerException.class),
new TestData(null, true, 0, "", 0, 0, NullPointerException.class), new TestData(null, true, 0, null, 0, 0, NullPointerException.class),
new TestData("Abc", true, 0, "abc", 0, 3, true), new TestData(null, true, 0, "", 0, 0, NullPointerException.class),
new TestData("Abc", false, 0, "abc", 0, 3, false), new TestData("Abc", true, 0, "abc", 0, 3, true),
new TestData("Abc", true, 1, "abc", 1, 2, true), new TestData("Abc", false, 0, "abc", 0, 3, false),
new TestData("Abc", false, 1, "abc", 1, 2, true), new TestData("Abc", true, 1, "abc", 1, 2, true),
new TestData("Abcd", true, 1, "abcD", 1, 2, true), new TestData("Abc", false, 1, "abc", 1, 2, true),
new TestData("Abcd", false, 1, "abcD", 1, 2, true), new TestData("Abcd", true, 1, "abcD", 1, 2, true),
new TestData("Abcd", false, 1, "abcD", 1, 2, true),
// @formatter:on
}; };
static Stream<Arguments> lastIndexWithStandardCharSequence() { static Stream<Arguments> lastIndexWithStandardCharSequence() {
// @formatter:off
return Stream.of( return Stream.of(
arguments("abc", "b", 2, 1), arguments("abc", "b", 2, 1),
arguments(new StringBuilder("abc"), "b", 2, 1), arguments(new StringBuilder("abc"), "b", 2, 1),
@ -168,6 +174,7 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
arguments(new StringBuffer("abc"), new StringBuffer("b"), 2, 1), arguments(new StringBuffer("abc"), new StringBuffer("b"), 2, 1),
arguments(new StringBuilder("abc"), new StringBuffer("b"), 2, 1) arguments(new StringBuilder("abc"), new StringBuffer("b"), 2, 1)
); );
// @formatter:on
} }
@Test @Test
@ -182,8 +189,7 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
@ParameterizedTest @ParameterizedTest
@MethodSource("lastIndexWithStandardCharSequence") @MethodSource("lastIndexWithStandardCharSequence")
public void testLastIndexOfWithDifferentCharSequences(final CharSequence cs, final CharSequence search, final int start, public void testLastIndexOfWithDifferentCharSequences(final CharSequence cs, final CharSequence search, final int start, final int expected) {
final int expected) {
assertEquals(expected, CharSequenceUtils.lastIndexOf(cs, search, start)); assertEquals(expected, CharSequenceUtils.lastIndexOf(cs, search, start));
} }
@ -240,11 +246,9 @@ public class CharSequenceUtilsTest extends AbstractLangTest {
} }
private void testNewLastIndexOfSingleSingle(final CharSequence a, final CharSequence b, final int start) { private void testNewLastIndexOfSingleSingle(final CharSequence a, final CharSequence b, final int start) {
assertEquals( assertEquals(a.toString().lastIndexOf(b.toString(), start),
a.toString().lastIndexOf(b.toString(), start),
CharSequenceUtils.lastIndexOf(new WrapperString(a.toString()), new WrapperString(b.toString()), start), CharSequenceUtils.lastIndexOf(new WrapperString(a.toString()), new WrapperString(b.toString()), start),
"testNewLastIndexOf fails! original : " + a + " seg : " + b + " start : " + start "testNewLastIndexOf fails! original : " + a + " seg : " + b + " start : " + start);
);
} }
@Test @Test

View File

@ -40,8 +40,8 @@ public class HashSetvBitSetTest extends AbstractLangTest {
private static int[] extractIndices(final BitSet coll) { private static int[] extractIndices(final BitSet coll) {
final int[] result = new int[coll.cardinality()]; final int[] result = new int[coll.cardinality()];
int i = 0; int i = 0;
int j=0; int j = 0;
while ((j=coll.nextSetBit(j)) != -1) { while ((j = coll.nextSetBit(j)) != -1) {
result[i++] = j++; result[i++] = j++;
} }
return result; return result;

View File

@ -46,6 +46,7 @@ public class RandomStringUtilsTest extends AbstractLangTest {
/** /**
* Computes Chi-Square statistic given observed and expected counts * Computes Chi-Square statistic given observed and expected counts
*
* @param observed array of observed frequency counts * @param observed array of observed frequency counts
* @param expected array of expected frequency counts * @param expected array of expected frequency counts
*/ */
@ -59,9 +60,7 @@ public class RandomStringUtilsTest extends AbstractLangTest {
} }
/** /**
* Test for LANG-1286. Creates situation where old code would * Test for LANG-1286. Creates situation where old code would overflow a char and result in a code point outside the specified range.
* overflow a char and result in a code point outside the specified
* range.
*/ */
@Test @Test
public void testCharOverflow() { public void testCharOverflow() {
@ -69,8 +68,7 @@ public class RandomStringUtilsTest extends AbstractLangTest {
final int end = Integer.MAX_VALUE; final int end = Integer.MAX_VALUE;
@SuppressWarnings("serial") @SuppressWarnings("serial")
final final Random fixedRandom = new Random() {
Random fixedRandom = new Random() {
@Override @Override
public int nextInt(final int n) { public int nextInt(final int n) {
// Prevents selection of 'start' as the character // Prevents selection of 'start' as the character
@ -95,7 +93,7 @@ public class RandomStringUtilsTest extends AbstractLangTest {
@Test @Test
public void testExceptions() { public void testExceptions() {
final char[] DUMMY = {'a'}; // valid char array final char[] DUMMY = { 'a' }; // valid char array
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1)); assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, true, true)); assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, true, true));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, DUMMY)); assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, DUMMY));
@ -104,9 +102,7 @@ public class RandomStringUtilsTest extends AbstractLangTest {
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, (String) null)); 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));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY)); assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY));
assertThrows( assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(-1, 'a', 'z', false, false, DUMMY, new Random()));
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, 48, false, true));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(8, 32, 65, true, false)); assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(8, 32, 65, true, false));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.randomAlphabetic(-1)); assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.randomAlphabetic(-1));
@ -117,8 +113,7 @@ public class RandomStringUtilsTest extends AbstractLangTest {
} }
/** /**
* Checks if the string got by {@link RandomStringUtils#random(int)} * Checks if the string got by {@link RandomStringUtils#random(int)} can be converted to UTF-8 and back without loss.
* can be converted to UTF-8 and back without loss.
* *
* @see <a href="https://issues.apache.org/jira/browse/LANG-100">LANG-100</a> * @see <a href="https://issues.apache.org/jira/browse/LANG-100">LANG-100</a>
*/ */
@ -131,12 +126,11 @@ public class RandomStringUtilsTest extends AbstractLangTest {
final String copy = new String(bytes, charset); final String copy = new String(bytes, charset);
// for a verbose compare: // for a verbose compare:
for (int i=0; i < orig.length() && i < copy.length(); i++) { for (int i = 0; i < orig.length() && i < copy.length(); i++) {
final char o = orig.charAt(i); final char o = orig.charAt(i);
final char c = copy.charAt(i); final char c = copy.charAt(i);
assertEquals(o, c, assertEquals(o, c, "differs at " + i + "(" + Integer.toHexString(Character.valueOf(o).hashCode()) + ","
"differs at " + i + "(" + Integer.toHexString(Character.valueOf(o).hashCode()) + "," + + Integer.toHexString(Character.valueOf(c).hashCode()) + ")");
Integer.toHexString(Character.valueOf(c).hashCode()) + ")");
} }
// compare length also // compare length also
assertEquals(orig.length(), copy.length()); assertEquals(orig.length(), copy.length());
@ -147,26 +141,24 @@ public class RandomStringUtilsTest extends AbstractLangTest {
@Test @Test
public void testLANG805() { public void testLANG805() {
final long seedMillis = System.currentTimeMillis(); final long seedMillis = System.currentTimeMillis();
assertEquals("aaa", RandomStringUtils.random(3, 0, 0, false, false, new char[]{'a'}, new Random(seedMillis))); assertEquals("aaa", RandomStringUtils.random(3, 0, 0, false, false, new char[] { 'a' }, new Random(seedMillis)));
} }
@Test @Test
public void testLANG807() { public void testLANG807() {
final IllegalArgumentException ex = final IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(3, 5, 5, false, false));
assertThrows(IllegalArgumentException.class, () -> RandomStringUtils.random(3, 5, 5, false, false));
final String msg = ex.getMessage(); final String msg = ex.getMessage();
assertTrue(msg.contains("start"), "Message (" + msg + ") must contain 'start'"); assertTrue(msg.contains("start"), "Message (" + msg + ") must contain 'start'");
assertTrue(msg.contains("end"), "Message (" + msg + ") must contain 'end'"); assertTrue(msg.contains("end"), "Message (" + msg + ") must contain 'end'");
} }
/** /**
* Make sure boundary alpha characters are generated by randomAlphabetic * Make sure boundary alpha characters are generated by randomAlphabetic This test will fail randomly with probability = 4 * (51/52)**1000 ~ 1.58E-8
* This test will fail randomly with probability = 4 * (51/52)**1000 ~ 1.58E-8
*/ */
@Test @Test
public void testRandomAlphabetic() { public void testRandomAlphabetic() {
final char[] testChars = {'a', 'z', 'A', 'Z'}; final char[] testChars = { 'a', 'z', 'A', 'Z' };
final boolean[] found = {false, false, false, false}; final boolean[] found = { false, false, false, false };
for (int i = 0; i < LOOP_COUNT; i++) { for (int i = 0; i < LOOP_COUNT; i++) {
final String randString = RandomStringUtils.randomAlphabetic(10); final String randString = RandomStringUtils.randomAlphabetic(10);
for (int j = 0; j < testChars.length; j++) { for (int j = 0; j < testChars.length; j++) {
@ -176,9 +168,7 @@ public class RandomStringUtilsTest extends AbstractLangTest {
} }
} }
for (int i = 0; i < testChars.length; i++) { for (int i = 0; i < testChars.length; i++) {
assertTrue(found[i], assertTrue(found[i], "alphanumeric character not generated in 1000 attempts: " + testChars[i] + " -- repeated failures indicate a problem ");
"alphanumeric character not generated in 1000 attempts: " + testChars[i] +
" -- repeated failures indicate a problem ");
} }
} }
@ -208,13 +198,12 @@ public class RandomStringUtilsTest extends AbstractLangTest {
} }
/** /**
* Make sure boundary alphanumeric characters are generated by randomAlphaNumeric * Make sure boundary alphanumeric characters are generated by randomAlphaNumeric This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7
* This test will fail randomly with probability = 6 * (61/62)**1000 ~ 5.2E-7
*/ */
@Test @Test
public void testRandomAlphaNumeric() { public void testRandomAlphaNumeric() {
final char[] testChars = {'a', 'z', 'A', 'Z', '0', '9'}; final char[] testChars = { 'a', 'z', 'A', 'Z', '0', '9' };
final boolean[] found = {false, false, false, false, false, false}; final boolean[] found = { false, false, false, false, false, false };
for (int i = 0; i < LOOP_COUNT; i++) { for (int i = 0; i < LOOP_COUNT; i++) {
final String randString = RandomStringUtils.randomAlphanumeric(10); final String randString = RandomStringUtils.randomAlphanumeric(10);
for (int j = 0; j < testChars.length; j++) { for (int j = 0; j < testChars.length; j++) {
@ -224,9 +213,7 @@ public class RandomStringUtilsTest extends AbstractLangTest {
} }
} }
for (int i = 0; i < testChars.length; i++) { for (int i = 0; i < testChars.length; i++) {
assertTrue(found[i], assertTrue(found[i], "alphanumeric character not generated in 1000 attempts: " + testChars[i] + " -- repeated failures indicate a problem ");
"alphanumeric character not generated in 1000 attempts: " +
testChars[i] + " -- repeated failures indicate a problem ");
} }
} }
@ -256,13 +243,12 @@ public class RandomStringUtilsTest extends AbstractLangTest {
} }
/** /**
* Make sure 32 and 127 are generated by randomNumeric * Make sure 32 and 127 are generated by randomNumeric This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5
* This test will fail randomly with probability = 2*(95/96)**1000 ~ 5.7E-5
*/ */
@Test @Test
public void testRandomAscii() { public void testRandomAscii() {
final char[] testChars = {(char) 32, (char) 126}; final char[] testChars = { (char) 32, (char) 126 };
final boolean[] found = {false, false}; final boolean[] found = { false, false };
// Test failures have been observed on GitHub builds with a 100 limit. // Test failures have been observed on GitHub builds with a 100 limit.
for (int i = 0; i < LOOP_COUNT; i++) { for (int i = 0; i < LOOP_COUNT; i++) {
final String randString = RandomStringUtils.randomAscii(10); final String randString = RandomStringUtils.randomAscii(10);
@ -273,9 +259,7 @@ public class RandomStringUtilsTest extends AbstractLangTest {
} }
} }
for (int i = 0; i < testChars.length; i++) { for (int i = 0; i < testChars.length; i++) {
assertTrue(found[i], assertTrue(found[i], "ascii character not generated in 1000 attempts: " + (int) testChars[i] + " -- repeated failures indicate a problem");
"ascii character not generated in 1000 attempts: " + (int) testChars[i] +
" -- repeated failures indicate a problem");
} }
} }
@ -330,13 +314,12 @@ public class RandomStringUtilsTest extends AbstractLangTest {
} }
/** /**
* Make sure '0' and '9' are generated by randomNumeric * Make sure '0' and '9' are generated by randomNumeric This test will fail randomly with probability = 2 * (9/10)**1000 ~ 3.5E-46
* This test will fail randomly with probability = 2 * (9/10)**1000 ~ 3.5E-46
*/ */
@Test @Test
public void testRandomNumeric() { public void testRandomNumeric() {
final char[] testChars = {'0', '9'}; final char[] testChars = { '0', '9' };
final boolean[] found = {false, false}; final boolean[] found = { false, false };
for (int i = 0; i < LOOP_COUNT; i++) { for (int i = 0; i < LOOP_COUNT; i++) {
final String randString = RandomStringUtils.randomNumeric(10); final String randString = RandomStringUtils.randomNumeric(10);
for (int j = 0; j < testChars.length; j++) { for (int j = 0; j < testChars.length; j++) {
@ -346,9 +329,7 @@ public class RandomStringUtilsTest extends AbstractLangTest {
} }
} }
for (int i = 0; i < testChars.length; i++) { for (int i = 0; i < testChars.length; i++) {
assertTrue(found[i], assertTrue(found[i], "digit not generated in 1000 attempts: " + testChars[i] + " -- repeated failures indicate a problem ");
"digit not generated in 1000 attempts: " + testChars[i] +
" -- repeated failures indicate a problem ");
} }
} }
@ -501,36 +482,34 @@ public class RandomStringUtilsTest extends AbstractLangTest {
} }
/** /**
* Test homogeneity of random strings generated -- * Test homogeneity of random strings generated -- i.e., test that characters show up with expected frequencies in generated strings. Will fail randomly
* i.e., test that characters show up with expected frequencies * about 1 in 100,000 times. Repeated failures indicate a problem.
* in generated strings. Will fail randomly about 1 in 100,000 times.
* Repeated failures indicate a problem.
*/ */
@Test @Test
public void testRandomStringUtilsHomog() { public void testRandomStringUtilsHomog() {
final String set = "abc"; final String set = "abc";
final char[] chars = set.toCharArray(); final char[] chars = set.toCharArray();
final int[] counts = {0, 0, 0}; final int[] counts = { 0, 0, 0 };
final int[] expected = {200, 200, 200}; final int[] expected = { 200, 200, 200 };
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
final String gen = RandomStringUtils.random(6, chars); final String gen = RandomStringUtils.random(6, chars);
for (int j = 0; j < 6; j++) { for (int j = 0; j < 6; j++) {
switch (gen.charAt(j)) { switch (gen.charAt(j)) {
case 'a': { case 'a': {
counts[0]++; counts[0]++;
break; break;
} }
case 'b': { case 'b': {
counts[1]++; counts[1]++;
break; break;
} }
case 'c': { case 'c': {
counts[2]++; counts[2]++;
break; break;
} }
default: { default: {
fail("generated character not in set"); fail("generated character not in set");
} }
} }
} }
} }
@ -540,4 +519,3 @@ public class RandomStringUtilsTest extends AbstractLangTest {
assertThat("test homogeneity -- will fail about 1 in 100,000 times", chiSquare(expected, counts), lessThan(23.025850929940457d)); assertThat("test homogeneity -- will fail about 1 in 100,000 times", chiSquare(expected, counts), lessThan(23.025850929940457d));
} }
} }

View File

@ -80,11 +80,9 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
final String actual = StringEscapeUtils.unescapeJava(original); final String actual = StringEscapeUtils.unescapeJava(original);
assertEquals(expected, actual, assertEquals(expected, actual,
"unescape(String) failed" + "unescape(String) failed" + (message == null ? "" : ": " + message) + ": expected '" + StringEscapeUtils.escapeJava(expected) +
(message == null ? "" : ": " + message) +
": expected '" + StringEscapeUtils.escapeJava(expected) +
// we escape this so we can see it in the error message // we escape this so we can see it in the error message
"' actual '" + StringEscapeUtils.escapeJava(actual) + "'"); "' actual '" + StringEscapeUtils.escapeJava(actual) + "'");
final StringWriter writer = new StringWriter(); final StringWriter writer = new StringWriter();
StringEscapeUtils.UNESCAPE_JAVA.translate(original, writer); StringEscapeUtils.UNESCAPE_JAVA.translate(original, writer);
@ -122,23 +120,23 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
@Test @Test
public void testEscapeCsvString() { public void testEscapeCsvString() {
assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar")); assertEquals("foo.bar", StringEscapeUtils.escapeCsv("foo.bar"));
assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar")); assertEquals("\"foo,bar\"", StringEscapeUtils.escapeCsv("foo,bar"));
assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar")); assertEquals("\"foo\nbar\"", StringEscapeUtils.escapeCsv("foo\nbar"));
assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar")); assertEquals("\"foo\rbar\"", StringEscapeUtils.escapeCsv("foo\rbar"));
assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar")); assertEquals("\"foo\"\"bar\"", StringEscapeUtils.escapeCsv("foo\"bar"));
assertEquals("foo\uD84C\uDFB4bar", StringEscapeUtils.escapeCsv("foo\uD84C\uDFB4bar")); assertEquals("foo\uD84C\uDFB4bar", StringEscapeUtils.escapeCsv("foo\uD84C\uDFB4bar"));
assertEquals("", StringEscapeUtils.escapeCsv("")); assertEquals("", StringEscapeUtils.escapeCsv(""));
assertNull(StringEscapeUtils.escapeCsv(null)); assertNull(StringEscapeUtils.escapeCsv(null));
} }
@Test @Test
public void testEscapeCsvWriter() throws Exception { public void testEscapeCsvWriter() throws Exception {
checkCsvEscapeWriter("foo.bar", "foo.bar"); checkCsvEscapeWriter("foo.bar", "foo.bar");
checkCsvEscapeWriter("\"foo,bar\"", "foo,bar"); checkCsvEscapeWriter("\"foo,bar\"", "foo,bar");
checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar"); checkCsvEscapeWriter("\"foo\nbar\"", "foo\nbar");
checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar"); checkCsvEscapeWriter("\"foo\rbar\"", "foo\rbar");
checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar"); checkCsvEscapeWriter("\"foo\"\"bar\"", "foo\"bar");
checkCsvEscapeWriter("foo\uD84C\uDFB4bar", "foo\uD84C\uDFB4bar"); checkCsvEscapeWriter("foo\uD84C\uDFB4bar", "foo\uD84C\uDFB4bar");
checkCsvEscapeWriter("", null); checkCsvEscapeWriter("", null);
checkCsvEscapeWriter("", ""); checkCsvEscapeWriter("", "");
@ -163,10 +161,9 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
// Some random Japanese Unicode characters // Some random Japanese Unicode characters
final String original = "\u304B\u304C\u3068"; final String original = "\u304B\u304C\u3068";
final String escaped = StringEscapeUtils.escapeHtml4(original); final String escaped = StringEscapeUtils.escapeHtml4(original);
assertEquals(original, escaped, assertEquals(original, escaped, "Hiragana character Unicode behavior should not be being escaped by escapeHtml4");
"Hiragana character Unicode behavior should not be being escaped by escapeHtml4");
final String unescaped = StringEscapeUtils.unescapeHtml4( escaped ); final String unescaped = StringEscapeUtils.unescapeHtml4(escaped);
assertEquals(escaped, unescaped, "Hiragana character Unicode behavior has changed - expected no unescaping"); assertEquals(escaped, unescaped, "Hiragana character Unicode behavior has changed - expected no unescaping");
} }
@ -198,10 +195,10 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
final String original = new String(data, StandardCharsets.UTF_8); final String original = new String(data, StandardCharsets.UTF_8);
final String escaped = StringEscapeUtils.escapeHtml4( original ); final String escaped = StringEscapeUtils.escapeHtml4(original);
assertEquals(original, escaped, "High Unicode should not have been escaped"); assertEquals(original, escaped, "High Unicode should not have been escaped");
final String unescaped = StringEscapeUtils.unescapeHtml4( escaped ); final String unescaped = StringEscapeUtils.unescapeHtml4(escaped);
assertEquals(original, unescaped, "High Unicode should have been unchanged"); assertEquals(original, unescaped, "High Unicode should have been unchanged");
// TODO: I think this should hold, needs further investigation // TODO: I think this should hold, needs further investigation
@ -235,12 +232,9 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
assertEscapeJava("\\u0001", "\u0001"); assertEscapeJava("\\u0001", "\u0001");
assertEscapeJava("Should use capitalized Unicode hex", "\\uABCD", "\uabcd"); assertEscapeJava("Should use capitalized Unicode hex", "\\uABCD", "\uabcd");
assertEscapeJava("He didn't say, \\\"stop!\\\"", assertEscapeJava("He didn't say, \\\"stop!\\\"", "He didn't say, \"stop!\"");
"He didn't say, \"stop!\""); assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0", "This space is non-breaking:\u00a0");
assertEscapeJava("non-breaking space", "This space is non-breaking:" + "\\u00A0", assertEscapeJava("\\uABCD\\u1234\\u012C", "\uABCD\u1234\u012C");
"This space is non-breaking:\u00a0");
assertEscapeJava("\\uABCD\\u1234\\u012C",
"\uABCD\u1234\u012C");
} }
/** /**
@ -254,8 +248,7 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
final String actual = StringEscapeUtils.escapeJava(input); final String actual = StringEscapeUtils.escapeJava(input);
/* /*
* In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape * In 2.4 StringEscapeUtils.escapeJava(String) escapes '/' characters, which are not a valid character to escape in a Java string.
* in a Java string.
*/ */
assertEquals(expected, actual); assertEquals(expected, actual);
} }
@ -269,7 +262,7 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
assertEquals("He didn't say, \\\"stop!\\\"", StringEscapeUtils.escapeJson("He didn't say, \"stop!\"")); assertEquals("He didn't say, \\\"stop!\\\"", StringEscapeUtils.escapeJson("He didn't say, \"stop!\""));
final String expected = "\\\"foo\\\" isn't \\\"bar\\\". specials: \\b\\r\\n\\f\\t\\\\\\/"; final String expected = "\\\"foo\\\" isn't \\\"bar\\\". specials: \\b\\r\\n\\f\\t\\\\\\/";
final String input ="\"foo\" isn't \"bar\". specials: \b\r\n\f\t\\/"; final String input = "\"foo\" isn't \"bar\". specials: \b\r\n\f\t\\/";
assertEquals(expected, StringEscapeUtils.escapeJson(input)); assertEquals(expected, StringEscapeUtils.escapeJson(input));
} }
@ -281,12 +274,9 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
assertEquals("\u00A1", StringEscapeUtils.escapeXml("\u00A1"), "XML should not escape >0x7f values"); assertEquals("\u00A1", StringEscapeUtils.escapeXml("\u00A1"), "XML should not escape >0x7f values");
assertEquals("\u00A0", StringEscapeUtils.unescapeXml("&#160;"), "XML should be able to unescape >0x7f values"); assertEquals("\u00A0", StringEscapeUtils.unescapeXml("&#160;"), "XML should be able to unescape >0x7f values");
assertEquals("\u00A0", StringEscapeUtils.unescapeXml("&#0160;"), assertEquals("\u00A0", StringEscapeUtils.unescapeXml("&#0160;"), "XML should be able to unescape >0x7f values with one leading 0");
"XML should be able to unescape >0x7f values with one leading 0"); assertEquals("\u00A0", StringEscapeUtils.unescapeXml("&#00160;"), "XML should be able to unescape >0x7f values with two leading 0s");
assertEquals("\u00A0", StringEscapeUtils.unescapeXml("&#00160;"), assertEquals("\u00A0", StringEscapeUtils.unescapeXml("&#000160;"), "XML should be able to unescape >0x7f values with three leading 0s");
"XML should be able to unescape >0x7f values with two leading 0s");
assertEquals("\u00A0", StringEscapeUtils.unescapeXml("&#000160;"),
"XML should be able to unescape >0x7f values with three leading 0s");
assertEquals("ain't", StringEscapeUtils.unescapeXml("ain&apos;t")); assertEquals("ain't", StringEscapeUtils.unescapeXml("ain&apos;t"));
assertEquals("ain&apos;t", StringEscapeUtils.escapeXml("ain't")); assertEquals("ain&apos;t", StringEscapeUtils.escapeXml("ain't"));
@ -309,12 +299,9 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
assertEquals("a\tb\rc\nd", StringEscapeUtils.escapeXml10("a\tb\rc\nd"), "XML 1.0 should not escape \t \n \r"); assertEquals("a\tb\rc\nd", StringEscapeUtils.escapeXml10("a\tb\rc\nd"), "XML 1.0 should not escape \t \n \r");
assertEquals("ab", StringEscapeUtils.escapeXml10("a\u0000\u0001\u0008\u000b\u000c\u000e\u001fb"), assertEquals("ab", StringEscapeUtils.escapeXml10("a\u0000\u0001\u0008\u000b\u000c\u000e\u001fb"),
"XML 1.0 should omit most #x0-x8 | #xb | #xc | #xe-#x19"); "XML 1.0 should omit most #x0-x8 | #xb | #xc | #xe-#x19");
assertEquals("a\ud7ff \ue000b", StringEscapeUtils.escapeXml10("a\ud7ff\ud800 \udfff \ue000b"), assertEquals("a\ud7ff \ue000b", StringEscapeUtils.escapeXml10("a\ud7ff\ud800 \udfff \ue000b"), "XML 1.0 should omit #xd800-#xdfff");
"XML 1.0 should omit #xd800-#xdfff"); assertEquals("a\ufffdb", StringEscapeUtils.escapeXml10("a\ufffd\ufffe\uffffb"), "XML 1.0 should omit #xfffe | #xffff");
assertEquals("a\ufffdb", StringEscapeUtils.escapeXml10("a\ufffd\ufffe\uffffb"), assertEquals("a\u007e&#127;&#132;\u0085&#134;&#159;\u00a0b", StringEscapeUtils.escapeXml10("a\u007e\u007f\u0084\u0085\u0086\u009f\u00a0b"),
"XML 1.0 should omit #xfffe | #xffff");
assertEquals("a\u007e&#127;&#132;\u0085&#134;&#159;\u00a0b",
StringEscapeUtils.escapeXml10("a\u007e\u007f\u0084\u0085\u0086\u009f\u00a0b"),
"XML 1.0 should escape #x7f-#x84 | #x86 - #x9f, for XML 1.1 compatibility"); "XML 1.0 should escape #x7f-#x84 | #x86 - #x9f, for XML 1.1 compatibility");
} }
@ -323,16 +310,12 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
assertEquals("a&lt;b&gt;c&quot;d&apos;e&amp;f", StringEscapeUtils.escapeXml11("a<b>c\"d'e&f")); assertEquals("a&lt;b&gt;c&quot;d&apos;e&amp;f", StringEscapeUtils.escapeXml11("a<b>c\"d'e&f"));
assertEquals("a\tb\rc\nd", StringEscapeUtils.escapeXml11("a\tb\rc\nd"), "XML 1.1 should not escape \t \n \r"); assertEquals("a\tb\rc\nd", StringEscapeUtils.escapeXml11("a\tb\rc\nd"), "XML 1.1 should not escape \t \n \r");
assertEquals("ab", StringEscapeUtils.escapeXml11("a\u0000b"), "XML 1.1 should omit #x0"); assertEquals("ab", StringEscapeUtils.escapeXml11("a\u0000b"), "XML 1.1 should omit #x0");
assertEquals("a&#1;&#8;&#11;&#12;&#14;&#31;b", assertEquals("a&#1;&#8;&#11;&#12;&#14;&#31;b", StringEscapeUtils.escapeXml11("a\u0001\u0008\u000b\u000c\u000e\u001fb"),
StringEscapeUtils.escapeXml11("a\u0001\u0008\u000b\u000c\u000e\u001fb"),
"XML 1.1 should escape #x1-x8 | #xb | #xc | #xe-#x19"); "XML 1.1 should escape #x1-x8 | #xb | #xc | #xe-#x19");
assertEquals("a\u007e&#127;&#132;\u0085&#134;&#159;\u00a0b", assertEquals("a\u007e&#127;&#132;\u0085&#134;&#159;\u00a0b", StringEscapeUtils.escapeXml11("a\u007e\u007f\u0084\u0085\u0086\u009f\u00a0b"),
StringEscapeUtils.escapeXml11("a\u007e\u007f\u0084\u0085\u0086\u009f\u00a0b"),
"XML 1.1 should escape #x7F-#x84 | #x86-#x9F"); "XML 1.1 should escape #x7F-#x84 | #x86-#x9F");
assertEquals("a\ud7ff \ue000b", StringEscapeUtils.escapeXml11("a\ud7ff\ud800 \udfff \ue000b"), assertEquals("a\ud7ff \ue000b", StringEscapeUtils.escapeXml11("a\ud7ff\ud800 \udfff \ue000b"), "XML 1.1 should omit #xd800-#xdfff");
"XML 1.1 should omit #xd800-#xdfff"); assertEquals("a\ufffdb", StringEscapeUtils.escapeXml11("a\ufffd\ufffe\uffffb"), "XML 1.1 should omit #xfffe | #xffff");
assertEquals("a\ufffdb", StringEscapeUtils.escapeXml11("a\ufffd\ufffe\uffffb"),
"XML 1.1 should omit #xfffe | #xffff");
} }
@Test @Test
@ -340,9 +323,9 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
// https://www.w3.org/TR/xml/#charsets says: // https://www.w3.org/TR/xml/#charsets says:
// Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character,
// excluding the surrogate blocks, FFFE, and FFFF. */ // excluding the surrogate blocks, FFFE, and FFFF. */
final CharSequenceTranslator escapeXml = StringEscapeUtils.ESCAPE_XML final CharSequenceTranslator escapeXml = StringEscapeUtils.ESCAPE_XML.with(NumericEntityEscaper.below(9), NumericEntityEscaper.between(0xB, 0xC),
.with(NumericEntityEscaper.below(9), NumericEntityEscaper.between(0xB, 0xC), NumericEntityEscaper.between(0xE, 0x19), NumericEntityEscaper.between(0xE, 0x19), NumericEntityEscaper.between(0xD800, 0xDFFF), NumericEntityEscaper.between(0xFFFE, 0xFFFF),
NumericEntityEscaper.between(0xD800, 0xDFFF), NumericEntityEscaper.between(0xFFFE, 0xFFFF), NumericEntityEscaper.above(0x110000)); NumericEntityEscaper.above(0x110000));
assertEquals("&#0;&#1;&#2;&#3;&#4;&#5;&#6;&#7;&#8;", escapeXml.translate("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008")); assertEquals("&#0;&#1;&#2;&#3;&#4;&#5;&#6;&#7;&#8;", escapeXml.translate("\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\u0008"));
assertEquals("\t", escapeXml.translate("\t")); // 0x9 assertEquals("\t", escapeXml.translate("\t")); // 0x9
@ -358,23 +341,19 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
* <p> * <p>
* From https://www.w3.org/International/questions/qa-escapes * From https://www.w3.org/International/questions/qa-escapes
* </p> * </p>
* <blockquote> * <blockquote> Supplementary characters are those Unicode characters that have code points higher than the characters in the Basic Multilingual Plane
* Supplementary characters are those Unicode characters that have code points higher than the characters in * (BMP). In UTF-16 a supplementary character is encoded using two 16-bit surrogate code points from the BMP. Because of this, some people think that
* the Basic Multilingual Plane (BMP). In UTF-16 a supplementary character is encoded using two 16-bit surrogate code points from the * supplementary characters need to be represented using two escapes, but this is incorrect - you must use the single, code point value for that character.
* BMP. Because of this, some people think that supplementary characters need to be represented using two escapes, but this is incorrect * For example, use &amp;&#35;x233B4&#59; rather than &amp;&#35;xD84C&#59;&amp;&#35;xDFB4&#59;. </blockquote>
* - you must use the single, code point value for that character. For example, use &amp;&#35;x233B4&#59; rather than *
* &amp;&#35;xD84C&#59;&amp;&#35;xDFB4&#59;.
* </blockquote>
* @see <a href="https://www.w3.org/International/questions/qa-escapes">Using character escapes in markup and CSS</a> * @see <a href="https://www.w3.org/International/questions/qa-escapes">Using character escapes in markup and CSS</a>
* @see <a href="https://issues.apache.org/jira/browse/LANG-728">LANG-728</a> * @see <a href="https://issues.apache.org/jira/browse/LANG-728">LANG-728</a>
*/ */
@Test @Test
public void testEscapeXmlSupplementaryCharacters() { public void testEscapeXmlSupplementaryCharacters() {
final CharSequenceTranslator escapeXml = final CharSequenceTranslator escapeXml = StringEscapeUtils.ESCAPE_XML.with(NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE));
StringEscapeUtils.ESCAPE_XML.with( NumericEntityEscaper.between(0x7f, Integer.MAX_VALUE) );
assertEquals("&#144308;", escapeXml.translate("\uD84C\uDFB4"), assertEquals("&#144308;", escapeXml.translate("\uD84C\uDFB4"), "Supplementary character must be represented using a single escape");
"Supplementary character must be represented using a single escape");
assertEquals("a b c &#144308;", escapeXml.translate("a b c \uD84C\uDFB4"), assertEquals("a b c &#144308;", escapeXml.translate("a b c \uD84C\uDFB4"),
"Supplementary characters mixed with basic characters should be encoded correctly"); "Supplementary characters mixed with basic characters should be encoded correctly");
@ -388,8 +367,7 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
/** /**
* Tests https://issues.apache.org/jira/browse/LANG-708 * Tests https://issues.apache.org/jira/browse/LANG-708
* *
* @throws IOException * @throws IOException if an I/O error occurs
* if an I/O error occurs
*/ */
@Test @Test
public void testLang708() throws IOException { public void testLang708() throws IOException {
@ -441,30 +419,30 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
@Test @Test
public void testUnescapeCsvString() { public void testUnescapeCsvString() {
assertEquals("foo.bar", StringEscapeUtils.unescapeCsv("foo.bar")); assertEquals("foo.bar", StringEscapeUtils.unescapeCsv("foo.bar"));
assertEquals("foo,bar", StringEscapeUtils.unescapeCsv("\"foo,bar\"")); assertEquals("foo,bar", StringEscapeUtils.unescapeCsv("\"foo,bar\""));
assertEquals("foo\nbar", StringEscapeUtils.unescapeCsv("\"foo\nbar\"")); assertEquals("foo\nbar", StringEscapeUtils.unescapeCsv("\"foo\nbar\""));
assertEquals("foo\rbar", StringEscapeUtils.unescapeCsv("\"foo\rbar\"")); assertEquals("foo\rbar", StringEscapeUtils.unescapeCsv("\"foo\rbar\""));
assertEquals("foo\"bar", StringEscapeUtils.unescapeCsv("\"foo\"\"bar\"")); assertEquals("foo\"bar", StringEscapeUtils.unescapeCsv("\"foo\"\"bar\""));
assertEquals("foo\uD84C\uDFB4bar", StringEscapeUtils.unescapeCsv("foo\uD84C\uDFB4bar")); assertEquals("foo\uD84C\uDFB4bar", StringEscapeUtils.unescapeCsv("foo\uD84C\uDFB4bar"));
assertEquals("", StringEscapeUtils.unescapeCsv("")); assertEquals("", StringEscapeUtils.unescapeCsv(""));
assertNull(StringEscapeUtils.unescapeCsv(null)); assertNull(StringEscapeUtils.unescapeCsv(null));
assertEquals("\"foo.bar\"", StringEscapeUtils.unescapeCsv("\"foo.bar\"")); assertEquals("\"foo.bar\"", StringEscapeUtils.unescapeCsv("\"foo.bar\""));
} }
@Test @Test
public void testUnescapeCsvWriter() throws Exception { public void testUnescapeCsvWriter() throws Exception {
checkCsvUnescapeWriter("foo.bar", "foo.bar"); checkCsvUnescapeWriter("foo.bar", "foo.bar");
checkCsvUnescapeWriter("foo,bar", "\"foo,bar\""); checkCsvUnescapeWriter("foo,bar", "\"foo,bar\"");
checkCsvUnescapeWriter("foo\nbar", "\"foo\nbar\""); checkCsvUnescapeWriter("foo\nbar", "\"foo\nbar\"");
checkCsvUnescapeWriter("foo\rbar", "\"foo\rbar\""); checkCsvUnescapeWriter("foo\rbar", "\"foo\rbar\"");
checkCsvUnescapeWriter("foo\"bar", "\"foo\"\"bar\""); checkCsvUnescapeWriter("foo\"bar", "\"foo\"\"bar\"");
checkCsvUnescapeWriter("foo\uD84C\uDFB4bar", "foo\uD84C\uDFB4bar"); checkCsvUnescapeWriter("foo\uD84C\uDFB4bar", "foo\uD84C\uDFB4bar");
checkCsvUnescapeWriter("", null); checkCsvUnescapeWriter("", null);
checkCsvUnescapeWriter("", ""); checkCsvUnescapeWriter("", "");
checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\""); checkCsvUnescapeWriter("\"foo.bar\"", "\"foo.bar\"");
} }
@Test @Test
@ -486,7 +464,7 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
// Test all Character values: // Test all Character values:
for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) { for (char i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) {
final Character c1 = Character.valueOf(i); final Character c1 = Character.valueOf(i);
final Character c2 = Character.valueOf((char) (i+1)); final Character c2 = Character.valueOf((char) (i + 1));
final String expected = c1.toString() + c2; final String expected = c1.toString() + c2;
final String escapedC1 = "&#x" + Integer.toHexString(c1.charValue()) + ";"; final String escapedC1 = "&#x" + Integer.toHexString(c1.charValue()) + ";";
final String escapedC2 = "&#x" + Integer.toHexString(c2.charValue()) + ";"; final String escapedC2 = "&#x" + Integer.toHexString(c2.charValue()) + ";";
@ -531,7 +509,7 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b"); assertUnescapeJava("\u123425foo\ntest\b", "\\u123425foo\\ntest\\b");
assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r"); assertUnescapeJava("'\foo\teste\r", "\\'\\foo\\teste\\r");
assertUnescapeJava("", "\\"); assertUnescapeJava("", "\\");
//foo // foo
assertUnescapeJava("lowercase Unicode", "\uABCDx", "\\uabcdx"); assertUnescapeJava("lowercase Unicode", "\uABCDx", "\\uabcdx");
assertUnescapeJava("uppercase Unicode", "\uABCDx", "\\uABCDx"); assertUnescapeJava("uppercase Unicode", "\uABCDx", "\\uABCDx");
assertUnescapeJava("Unicode as final character", "\uABCD", "\\uabcd"); assertUnescapeJava("Unicode as final character", "\uABCD", "\\uabcd");
@ -545,7 +523,7 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
assertEquals("He didn't say, \"stop!\"", StringEscapeUtils.unescapeJson("He didn't say, \\\"stop!\\\"")); assertEquals("He didn't say, \"stop!\"", StringEscapeUtils.unescapeJson("He didn't say, \\\"stop!\\\""));
final String expected ="\"foo\" isn't \"bar\". specials: \b\r\n\f\t\\/"; final String expected = "\"foo\" isn't \"bar\". specials: \b\r\n\f\t\\/";
final String input = "\\\"foo\\\" isn't \\\"bar\\\". specials: \\b\\r\\n\\f\\t\\\\\\/"; final String input = "\\\"foo\\\" isn't \\\"bar\\\". specials: \\b\\r\\n\\f\\t\\\\\\/";
assertEquals(expected, StringEscapeUtils.unescapeJson(input)); assertEquals(expected, StringEscapeUtils.unescapeJson(input));
@ -563,8 +541,7 @@ public class StringEscapeUtilsTest extends AbstractLangTest {
*/ */
@Test @Test
public void testUnescapeXmlSupplementaryCharacters() { public void testUnescapeXmlSupplementaryCharacters() {
assertEquals("\uD84C\uDFB4", StringEscapeUtils.unescapeXml("&#144308;"), assertEquals("\uD84C\uDFB4", StringEscapeUtils.unescapeXml("&#144308;"), "Supplementary character must be represented using a single escape");
"Supplementary character must be represented using a single escape");
assertEquals("a b c \uD84C\uDFB4", StringEscapeUtils.unescapeXml("a b c &#144308;"), assertEquals("a b c \uD84C\uDFB4", StringEscapeUtils.unescapeXml("a b c &#144308;"),
"Supplementary characters mixed with basic characters should be decoded correctly"); "Supplementary characters mixed with basic characters should be decoded correctly");

View File

@ -219,10 +219,10 @@ public class StringUtilsContainsTest extends AbstractLangTest {
assertFalse(StringUtils.containsAnyIgnoreCase("", new String[] { "hello" })); assertFalse(StringUtils.containsAnyIgnoreCase("", new String[] { "hello" }));
assertFalse(StringUtils.containsAnyIgnoreCase("hello, goodbye", (String[]) null)); assertFalse(StringUtils.containsAnyIgnoreCase("hello, goodbye", (String[]) null));
assertFalse(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[0])); assertFalse(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[0]));
assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"hello", "goodbye"})); assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[] { "hello", "goodbye" }));
assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"hello", "Goodbye"})); assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[] { "hello", "Goodbye" }));
assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"Hello", "Goodbye"})); assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[] { "Hello", "Goodbye" }));
assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[]{"Hello", null})); assertTrue(StringUtils.containsAnyIgnoreCase("hello, goodbye", new String[] { "Hello", null }));
assertTrue(StringUtils.containsAnyIgnoreCase("hello, null", new String[] { "Hello", null })); assertTrue(StringUtils.containsAnyIgnoreCase("hello, null", new String[] { "Hello", null }));
// Javadoc examples: // Javadoc examples:
assertTrue(StringUtils.containsAnyIgnoreCase("abcd", "ab", null)); assertTrue(StringUtils.containsAnyIgnoreCase("abcd", "ab", null));
@ -235,20 +235,17 @@ public class StringUtilsContainsTest extends AbstractLangTest {
public void testContainsIgnoreCase_LocaleIndependence() { public void testContainsIgnoreCase_LocaleIndependence() {
final Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() }; final Locale[] locales = { Locale.ENGLISH, new Locale("tr"), Locale.getDefault() };
final String[][] tdata = { { "i", "I" }, { "I", "i" }, { "\u03C2", "\u03C3" }, { "\u03A3", "\u03C2" }, final String[][] tdata = { { "i", "I" }, { "I", "i" }, { "\u03C2", "\u03C3" }, { "\u03A3", "\u03C2" }, { "\u03A3", "\u03C3" }, };
{ "\u03A3", "\u03C3" }, };
final String[][] fdata = { { "\u00DF", "SS" }, }; final String[][] fdata = { { "\u00DF", "SS" }, };
for (final Locale testLocale : locales) { for (final Locale testLocale : locales) {
Locale.setDefault(testLocale); Locale.setDefault(testLocale);
for (int j = 0; j < tdata.length; j++) { for (int j = 0; j < tdata.length; j++) {
assertTrue(StringUtils.containsIgnoreCase(tdata[j][0], tdata[j][1]), assertTrue(StringUtils.containsIgnoreCase(tdata[j][0], tdata[j][1]), Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1]);
Locale.getDefault() + ": " + j + " " + tdata[j][0] + " " + tdata[j][1]);
} }
for (int j = 0; j < fdata.length; j++) { for (int j = 0; j < fdata.length; j++) {
assertFalse(StringUtils.containsIgnoreCase(fdata[j][0], fdata[j][1]), assertFalse(StringUtils.containsIgnoreCase(fdata[j][0], fdata[j][1]), Locale.getDefault() + ": " + j + " " + fdata[j][0] + " " + fdata[j][1]);
Locale.getDefault() + ": " + j + " " + fdata[j][0] + " " + fdata[j][1]);
} }
} }
} }
@ -293,9 +290,9 @@ public class StringUtilsContainsTest extends AbstractLangTest {
final String str1 = "a"; final String str1 = "a";
final String str2 = "b"; final String str2 = "b";
final String str3 = "ab."; final String str3 = "ab.";
final char[] chars1= {'b'}; final char[] chars1 = { 'b' };
final char[] chars2= {'.'}; final char[] chars2 = { '.' };
final char[] chars3= {'c', 'd'}; final char[] chars3 = { 'c', 'd' };
final char[] emptyChars = {}; final char[] emptyChars = {};
assertTrue(StringUtils.containsNone(null, (char[]) null)); assertTrue(StringUtils.containsNone(null, (char[]) null));
assertTrue(StringUtils.containsNone("", (char[]) null)); assertTrue(StringUtils.containsNone("", (char[]) null));
@ -351,9 +348,9 @@ public class StringUtilsContainsTest extends AbstractLangTest {
final String str1 = "a"; final String str1 = "a";
final String str2 = "b"; final String str2 = "b";
final String str3 = "ab."; final String str3 = "ab.";
final String chars1= "b"; final String chars1 = "b";
final String chars2= "."; final String chars2 = ".";
final String chars3= "cd"; final String chars3 = "cd";
assertTrue(StringUtils.containsNone(null, (String) null)); assertTrue(StringUtils.containsNone(null, (String) null));
assertTrue(StringUtils.containsNone("", (String) null)); assertTrue(StringUtils.containsNone("", (String) null));
assertTrue(StringUtils.containsNone(null, "")); assertTrue(StringUtils.containsNone(null, ""));
@ -408,9 +405,9 @@ public class StringUtilsContainsTest extends AbstractLangTest {
final String str1 = "a"; final String str1 = "a";
final String str2 = "b"; final String str2 = "b";
final String str3 = "ab"; final String str3 = "ab";
final char[] chars1= {'b'}; final char[] chars1 = { 'b' };
final char[] chars2= {'a'}; final char[] chars2 = { 'a' };
final char[] chars3= {'a', 'b'}; final char[] chars3 = { 'a', 'b' };
final char[] emptyChars = {}; final char[] emptyChars = {};
assertFalse(StringUtils.containsOnly(null, (char[]) null)); assertFalse(StringUtils.containsOnly(null, (char[]) null));
assertFalse(StringUtils.containsOnly("", (char[]) null)); assertFalse(StringUtils.containsOnly("", (char[]) null));
@ -434,9 +431,9 @@ public class StringUtilsContainsTest extends AbstractLangTest {
final String str1 = "a"; final String str1 = "a";
final String str2 = "b"; final String str2 = "b";
final String str3 = "ab"; final String str3 = "ab";
final String chars1= "b"; final String chars1 = "b";
final String chars2= "a"; final String chars2 = "a";
final String chars3= "ab"; final String chars3 = "ab";
assertFalse(StringUtils.containsOnly(null, (String) null)); assertFalse(StringUtils.containsOnly(null, (String) null));
assertFalse(StringUtils.containsOnly("", (String) null)); assertFalse(StringUtils.containsOnly("", (String) null));
assertFalse(StringUtils.containsOnly(null, "")); assertFalse(StringUtils.containsOnly(null, ""));
@ -456,12 +453,12 @@ public class StringUtilsContainsTest extends AbstractLangTest {
@Test @Test
public void testContainsWhitespace() { public void testContainsWhitespace() {
assertFalse( StringUtils.containsWhitespace("") ); assertFalse(StringUtils.containsWhitespace(""));
assertTrue( StringUtils.containsWhitespace(" ") ); assertTrue(StringUtils.containsWhitespace(" "));
assertFalse( StringUtils.containsWhitespace("a") ); assertFalse(StringUtils.containsWhitespace("a"));
assertTrue( StringUtils.containsWhitespace("a ") ); assertTrue(StringUtils.containsWhitespace("a "));
assertTrue( StringUtils.containsWhitespace(" a") ); assertTrue(StringUtils.containsWhitespace(" a"));
assertTrue( StringUtils.containsWhitespace("a\t") ); assertTrue(StringUtils.containsWhitespace("a\t"));
assertTrue( StringUtils.containsWhitespace("\n") ); assertTrue(StringUtils.containsWhitespace("\n"));
} }
} }

View File

@ -359,7 +359,7 @@ public class StringUtilsTest extends AbstractLangTest {
assertAbbreviateWithAbbrevMarkerAndOffset("abcdefghi*", "*", 2, 10); assertAbbreviateWithAbbrevMarkerAndOffset("abcdefghi*", "*", 2, 10);
assertAbbreviateWithAbbrevMarkerAndOffset("abcdef{{{{", "{{{{", 4, 10); assertAbbreviateWithAbbrevMarkerAndOffset("abcdef{{{{", "{{{{", 4, 10);
assertAbbreviateWithAbbrevMarkerAndOffset("abcdef____", "____", 5, 10); assertAbbreviateWithAbbrevMarkerAndOffset("abcdef____", "____", 5, 10);
assertAbbreviateWithAbbrevMarkerAndOffset("==fghijk==", "==", 5, 10); assertAbbreviateWithAbbrevMarkerAndOffset(" == fghijk == ", " == ", 5, 10);
assertAbbreviateWithAbbrevMarkerAndOffset("___ghij___", "___", 6, 10); assertAbbreviateWithAbbrevMarkerAndOffset("___ghij___", "___", 6, 10);
assertAbbreviateWithAbbrevMarkerAndOffset("/ghijklmno", "/", 7, 10); assertAbbreviateWithAbbrevMarkerAndOffset("/ghijklmno", "/", 7, 10);
assertAbbreviateWithAbbrevMarkerAndOffset("/ghijklmno", "/", 8, 10); assertAbbreviateWithAbbrevMarkerAndOffset("/ghijklmno", "/", 8, 10);
@ -1367,7 +1367,7 @@ public class StringUtilsTest extends AbstractLangTest {
assertEquals("", StringUtils.join(EMPTY_STRING_LIST, null)); assertEquals("", StringUtils.join(EMPTY_STRING_LIST, null));
assertEquals("", StringUtils.join(EMPTY_STRING_LIST, "")); assertEquals("", StringUtils.join(EMPTY_STRING_LIST, ""));
assertEquals("", StringUtils.join(MIXED_STRING_LIST, "", 0, MIXED_STRING_LIST.size()- 1)); assertEquals("", StringUtils.join(MIXED_STRING_LIST, "", 0, MIXED_STRING_LIST.size() - 1));
} }
@ParameterizedTest @ParameterizedTest

View File

@ -173,7 +173,7 @@ public class HashCodeBuilderTest extends AbstractLangTest {
@Override @Override
public int hashCode() { public int hashCode() {
return b*17 + super.hashCode(); return b * 17 + super.hashCode();
} }
} }

View File

@ -333,70 +333,57 @@ public class JsonToStringStyleTest extends AbstractLangTest {
assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append(now).toString()); assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append(now).toString());
assertEquals("{\"now\":\"" + now +"\"}", new ToStringBuilder(base).append("now", now) assertEquals("{\"now\":\"" + now + "\"}", new ToStringBuilder(base).append("now", now).toString());
.toString()); assertEquals("{\"now\":\"" + now + "\",\"after\":\"" + afterNow + "\"}",
assertEquals("{\"now\":\"" + now +"\",\"after\":\"" + afterNow + "\"}", new ToStringBuilder(base).append("now", now).append("after", afterNow) new ToStringBuilder(base).append("now", now).append("after", afterNow).toString());
.toString());
} }
@Test @Test
public void testDoubleArray() { public void testDoubleArray() {
final double[] array = {1, 2, -3, 4}; final double[] array = { 1, 2, -3, 4 };
final ToStringBuilder toStringBuilder = new ToStringBuilder(base); final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString()); assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
assertEquals("{\"doubleArray\":[1.0,2.0,-3.0,4.0]}", toStringBuilder.append("doubleArray", array) assertEquals("{\"doubleArray\":[1.0,2.0,-3.0,4.0]}", toStringBuilder.append("doubleArray", array).toString());
.toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((long[]) null).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((long[]) null).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
} }
@Test @Test
public void testFloatArray() { public void testFloatArray() {
final float[] array = {1, 2, -3, 4}; final float[] array = { 1, 2, -3, 4 };
final ToStringBuilder toStringBuilder = new ToStringBuilder(base); final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString()); assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
assertEquals("{\"floatArray\":[1.0,2.0,-3.0,4.0]}", toStringBuilder.append("floatArray", array) assertEquals("{\"floatArray\":[1.0,2.0,-3.0,4.0]}", toStringBuilder.append("floatArray", array).toString());
.toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((long[]) null).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((long[]) null).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
} }
@Test @Test
public void testIntArray() { public void testIntArray() {
final int[] array = {1, 2, -3, 4}; final int[] array = { 1, 2, -3, 4 };
final ToStringBuilder toStringBuilder = new ToStringBuilder(base); final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString()); assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
assertEquals("{\"intArray\":[1,2,-3,4]}", toStringBuilder.append("intArray", array) assertEquals("{\"intArray\":[1,2,-3,4]}", toStringBuilder.append("intArray", array).toString());
.toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((long[]) null).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((long[]) null).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
} }
@Test @Test
@ -444,39 +431,32 @@ public class JsonToStringStyleTest extends AbstractLangTest {
@Test @Test
public void testLongArray() { public void testLongArray() {
final long[] array = {1, 2, -3, 4}; final long[] array = { 1, 2, -3, 4 };
final ToStringBuilder toStringBuilder = new ToStringBuilder(base); final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString()); assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
assertEquals("{\"longArray\":[1,2,-3,4]}", toStringBuilder.append("longArray", array) assertEquals("{\"longArray\":[1,2,-3,4]}", toStringBuilder.append("longArray", array).toString());
.toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((long[]) null).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((long[]) null).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
} }
@Test @Test
public void testLongArrayArray() { public void testLongArrayArray() {
final long[][] array = {{1, 2}, null, {5}}; final long[][] array = { { 1, 2 }, null, { 5 } };
final ToStringBuilder toStringBuilder = new ToStringBuilder(base); final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString()); assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((long[][]) null).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((long[][]) null).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
} }
@Test @Test
@ -498,18 +478,16 @@ public class JsonToStringStyleTest extends AbstractLangTest {
baseMap.put("k1", "v1"); baseMap.put("k1", "v1");
baseMap.put("k2", innerMap); baseMap.put("k2", innerMap);
final InnerMapObject object = new InnerMapObject(){ final InnerMapObject object = new InnerMapObject() {
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this).append("pid", this.pid) return new ToStringBuilder(this).append("pid", this.pid).append("map", this.map).toString();
.append("map", this.map).toString();
} }
}; };
object.pid = "dummy-text"; object.pid = "dummy-text";
object.map = baseMap; object.map = baseMap;
assertEquals("{\"object\":{\"pid\":\"dummy-text\",\"map\":{\"k1\":\"v1\"," + assertEquals("{\"object\":{\"pid\":\"dummy-text\",\"map\":{\"k1\":\"v1\"," + "\"k2\":{\"k2.1\":\"v2.1\",\"k2.2\":\"v2.2\"}}}}",
"\"k2\":{\"k2.1\":\"v2.1\",\"k2.2\":\"v2.2\"}}}}",
new ToStringBuilder(base).append("object", object).toString()); new ToStringBuilder(base).append("object", object).toString());
} }
@ -518,9 +496,7 @@ public class JsonToStringStyleTest extends AbstractLangTest {
final Person p = new Person() { final Person p = new Person() {
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this).append("name", this.name) return new ToStringBuilder(this).append("name", this.name).append("age", this.age).append("smoker", this.smoker).toString();
.append("age", this.age).append("smoker", this.smoker)
.toString();
} }
}; };
p.name = "Jane Doe"; p.name = "Jane Doe";
@ -528,14 +504,11 @@ public class JsonToStringStyleTest extends AbstractLangTest {
p.smoker = true; p.smoker = true;
final NestingPerson nestP = new NestingPerson(); final NestingPerson nestP = new NestingPerson();
nestP.pid="#1@Jane"; nestP.pid = "#1@Jane";
nestP.person = p; nestP.person = p;
assertEquals( assertEquals("{\"pid\":\"#1@Jane\",\"person\":{\"name\":\"Jane Doe\",\"age\":25,\"smoker\":true}}",
"{\"pid\":\"#1@Jane\",\"person\":{\"name\":\"Jane Doe\",\"age\":25,\"smoker\":true}}", new ToStringBuilder(nestP).append("pid", nestP.pid).append("person", nestP.person).toString());
new ToStringBuilder(nestP).append("pid", nestP.pid)
.append("person", nestP.person)
.toString());
} }
@Test @Test
@ -545,91 +518,55 @@ public class JsonToStringStyleTest extends AbstractLangTest {
@Test @Test
public void testObject() { public void testObject() {
final Integer i3 = Integer.valueOf(3); final Integer i3 = Integer.valueOf(3);
final Integer i4 = Integer.valueOf(4); final Integer i4 = Integer.valueOf(4);
assertThrows( assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((Object) null).toString());
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append((Object) null).toString());
assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append(i3).toString()); assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append(i3).toString());
assertEquals("{\"a\":null}", assertEquals("{\"a\":null}", new ToStringBuilder(base).append("a", (Object) null).toString());
new ToStringBuilder(base).append("a", (Object) null).toString()); assertEquals("{\"a\":3}", new ToStringBuilder(base).append("a", i3).toString());
assertEquals("{\"a\":3}", new ToStringBuilder(base).append("a", i3) assertEquals("{\"a\":3,\"b\":4}", new ToStringBuilder(base).append("a", i3).append("b", i4).toString());
.toString());
assertEquals("{\"a\":3,\"b\":4}",
new ToStringBuilder(base).append("a", i3).append("b", i4)
.toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append("a", i3, false).toString());
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append("a", i3, false).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString());
UnsupportedOperationException.class,
() -> new ToStringBuilder(base).append("a", new ArrayList<>(), false).toString());
assertEquals( assertEquals("{\"a\":[]}", new ToStringBuilder(base).append("a", new ArrayList<>(), true).toString());
"{\"a\":[]}",
new ToStringBuilder(base).append("a", new ArrayList<>(),
true).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append("a", new HashMap<>(), false).toString());
UnsupportedOperationException.class,
() -> new ToStringBuilder(base).append("a", new HashMap<>(), false).toString());
assertEquals( assertEquals("{\"a\":{}}", new ToStringBuilder(base).append("a", new HashMap<>(), true).toString());
"{\"a\":{}}",
new ToStringBuilder(base).append("a",
new HashMap<>(), true).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
UnsupportedOperationException.class,
() -> new ToStringBuilder(base).append("a", (Object) new String[0], false).toString());
assertEquals( assertEquals("{\"a\":[]}", new ToStringBuilder(base).append("a", (Object) new String[0], true).toString());
"{\"a\":[]}",
new ToStringBuilder(base).append("a", (Object) new String[0],
true).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> new ToStringBuilder(base).append("a", (Object) new int[] { 1, 2, 3 }, false).toString());
UnsupportedOperationException.class,
() -> new ToStringBuilder(base).append("a", (Object) new int[]{1, 2, 3}, false).toString());
assertEquals( assertEquals("{\"a\":[1,2,3]}", new ToStringBuilder(base).append("a", (Object) new int[] { 1, 2, 3 }, true).toString());
"{\"a\":[1,2,3]}",
new ToStringBuilder(base).append("a",
(Object) new int[]{1, 2, 3}, true).toString());
assertThrows( assertThrows(UnsupportedOperationException.class,
UnsupportedOperationException.class, () -> new ToStringBuilder(base).append("a", (Object) new String[] { "v", "x", "y", "z" }, false).toString());
() -> new ToStringBuilder(base).append("a", (Object) new String[]{"v", "x", "y", "z"}, false).toString());
assertEquals( assertEquals("{\"a\":[\"v\",\"x\",\"y\",\"z\"]}", new ToStringBuilder(base).append("a", (Object) new String[] { "v", "x", "y", "z" }, true).toString());
"{\"a\":[\"v\",\"x\",\"y\",\"z\"]}",
new ToStringBuilder(base).append("a",
(Object) new String[]{"v", "x", "y", "z"}, true)
.toString());
} }
@Test @Test
public void testObjectArray() { public void testObjectArray() {
final Object[] array = {null, base, new int[]{3, 6}}; final Object[] array = { null, base, new int[] { 3, 6 } };
final ToStringBuilder toStringBuilder = new ToStringBuilder(base); final ToStringBuilder toStringBuilder = new ToStringBuilder(base);
assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString()); assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append(array).toString());
assertEquals("{\"objectArray\":[null,5,[3,6]]}", toStringBuilder.append("objectArray", array) assertEquals("{\"objectArray\":[null,5,[3,6]]}", toStringBuilder.append("objectArray", array).toString());
.toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object[]) null).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object[]) null).toString());
assertThrows( assertThrows(UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
UnsupportedOperationException.class, () -> toStringBuilder.append((Object) array).toString());
} }
@Test @Test
@ -638,11 +575,10 @@ public class JsonToStringStyleTest extends AbstractLangTest {
map.put("k1", "value1"); map.put("k1", "value1");
map.put("k2", 2); map.put("k2", 2);
final InnerMapObject object = new InnerMapObject(){ final InnerMapObject object = new InnerMapObject() {
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this).append("pid", this.pid) return new ToStringBuilder(this).append("pid", this.pid).append("map", this.map).toString();
.append("map", this.map).toString();
} }
}; };
object.pid = "dummy-text"; object.pid = "dummy-text";

View File

@ -41,17 +41,19 @@ public class ToStringBuilderTest extends AbstractLangTest {
static final String staticString2 = "staticString2"; static final String staticString2 = "staticString2";
static final int staticInt2 = 67890; static final int staticInt2 = 67890;
} }
/** /**
* Points out failure to print anything from appendToString methods using MULTI_LINE_STYLE. * Points out failure to print anything from appendToString methods using MULTI_LINE_STYLE. See issue LANG-372.
* See issue LANG-372.
*/ */
final class MultiLineTestObject { final class MultiLineTestObject {
Integer i = Integer.valueOf(31337); Integer i = Integer.valueOf(31337);
@Override @Override
public String toString() { public String toString() {
return new ToStringBuilder(this).append("testInt", i).toString(); return new ToStringBuilder(this).append("testInt", i).toString();
} }
} }
static class ObjectCycle { static class ObjectCycle {
Object obj; Object obj;
@ -68,7 +70,9 @@ public class ToStringBuilderTest extends AbstractLangTest {
return ToStringBuilder.reflectionToString(this); return ToStringBuilder.reflectionToString(this);
} }
} }
Inner inner = new Inner(); Inner inner = new Inner();
@Override @Override
public String toString() { public String toString() {
return ToStringBuilder.reflectionToString(this); return ToStringBuilder.reflectionToString(this);
@ -115,16 +119,16 @@ public class ToStringBuilderTest extends AbstractLangTest {
static class ReflectionTestFixtureA { static class ReflectionTestFixtureA {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final char a='a'; private final char a = 'a';
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final transient char transientA='t'; private final transient char transientA = 't';
} }
static class ReflectionTestFixtureB extends ReflectionTestFixtureA { static class ReflectionTestFixtureB extends ReflectionTestFixtureA {
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final char b='b'; private final char b = 'b';
@SuppressWarnings("unused") @SuppressWarnings("unused")
private final transient char transientB='t'; private final transient char transientB = 't';
} }
private static final class SelfInstanceTwoVarsReflectionTestFixture { private static final class SelfInstanceTwoVarsReflectionTestFixture {
@ -144,7 +148,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
public String toString() { public String toString() {
return ToStringBuilder.reflectionToString(this); return ToStringBuilder.reflectionToString(this);
} }
} }
private static final class SelfInstanceVarReflectionTestFixture { private static final class SelfInstanceVarReflectionTestFixture {
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -158,7 +162,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
public String toString() { public String toString() {
return ToStringBuilder.reflectionToString(this); return ToStringBuilder.reflectionToString(this);
} }
} }
/** /**
* Test fixture for ReflectionToStringBuilder.toString() for statics. * Test fixture for ReflectionToStringBuilder.toString() for statics.
@ -194,7 +198,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
// //
// assertReflectionArray("<null>", array); // assertReflectionArray("<null>", array);
// //
// The expected value is not baseStr + "[<null>]" since array==null and is typed as Object. // The expected value is not baseStr + "[<null>]" since array == null and is typed as Object.
// The null array does not carry array type information. // The null array does not carry array type information.
// If we added a primitive array type constructor and pile of associated methods, // If we added a primitive array type constructor and pile of associated methods,
// then type declaring type information could be carried forward. IMHO, null is null. // then type declaring type information could be carried forward. IMHO, null is null.
@ -248,12 +252,9 @@ public class ToStringBuilderTest extends AbstractLangTest {
final Boolean objectToAppend2 = Boolean.TRUE; final Boolean objectToAppend2 = Boolean.TRUE;
final Object objectToAppend3 = new Object(); final Object objectToAppend3 = new Object();
assertEquals(baseStr + "[" + toBaseString(objectToAppend1) + "]", assertEquals(baseStr + "[" + toBaseString(objectToAppend1) + "]", new ToStringBuilder(base).appendAsObjectToString(objectToAppend1).toString());
new ToStringBuilder(base).appendAsObjectToString(objectToAppend1).toString()); assertEquals(baseStr + "[" + toBaseString(objectToAppend2) + "]", new ToStringBuilder(base).appendAsObjectToString(objectToAppend2).toString());
assertEquals(baseStr + "[" + toBaseString(objectToAppend2) + "]", assertEquals(baseStr + "[" + toBaseString(objectToAppend3) + "]", new ToStringBuilder(base).appendAsObjectToString(objectToAppend3).toString());
new ToStringBuilder(base).appendAsObjectToString(objectToAppend2).toString());
assertEquals(baseStr + "[" + toBaseString(objectToAppend3) + "]",
new ToStringBuilder(base).appendAsObjectToString(objectToAppend3).toString());
} }
@Test @Test
@ -266,10 +267,8 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendBooleanArrayWithFieldName() { public void testAppendBooleanArrayWithFieldName() {
final boolean[] array = { true, false, false }; final boolean[] array = { true, false, false };
assertEquals(baseStr + "[flags={true,false,false}]", assertEquals(baseStr + "[flags={true,false,false}]", new ToStringBuilder(base).append("flags", array).toString());
new ToStringBuilder(base).append("flags", array).toString()); assertEquals(baseStr + "[flags=<null>]", new ToStringBuilder(base).append("flags", (boolean[]) null).toString());
assertEquals(baseStr + "[flags=<null>]",
new ToStringBuilder(base).append("flags", (boolean[]) null).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString());
assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append(null, array).toString()); assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append(null, array).toString());
} }
@ -277,15 +276,12 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendBooleanArrayWithFieldNameAndFullDetail() { public void testAppendBooleanArrayWithFieldNameAndFullDetail() {
final boolean[] array = { true, false, false }; final boolean[] array = { true, false, false };
assertEquals(baseStr + "[flags={true,false,false}]", assertEquals(baseStr + "[flags={true,false,false}]", new ToStringBuilder(base).append("flags", array, true).toString());
new ToStringBuilder(base).append("flags", array, true).toString()); assertEquals(baseStr + "[length=<size=3>]", new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[length=<size=3>]", assertEquals(baseStr + "[flags=<null>]", new ToStringBuilder(base).append("flags", (boolean[]) null, true).toString());
new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[flags=<null>]",
new ToStringBuilder(base).append("flags", (boolean[]) null, true).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString());
assertEquals(baseStr + "[<size=3>]", new ToStringBuilder(base).append(null, array, false).toString()); assertEquals(baseStr + "[<size=3>]", new ToStringBuilder(base).append(null, array, false).toString());
} }
// Reflection Array Array tests // Reflection Array Array tests
@ -293,8 +289,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
public void testAppendByteArrayWithFieldName() { public void testAppendByteArrayWithFieldName() {
final byte[] array = { 1, 2, -3, 4 }; final byte[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString()); assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString());
assertEquals(baseStr + "[values=<null>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null).toString());
new ToStringBuilder(base).append("values", (boolean[]) null).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(null, array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(null, array).toString());
} }
@ -302,12 +297,9 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendByteArrayWithFieldNameAndFullDetail() { public void testAppendByteArrayWithFieldNameAndFullDetail() {
final byte[] array = { 1, 2, -3, 4 }; final byte[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[values={1,2,-3,4}]", assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array, true).toString());
new ToStringBuilder(base).append("values", array, true).toString()); assertEquals(baseStr + "[length=<size=4>]", new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[length=<size=4>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[values=<null>]",
new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString());
assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString()); assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString());
} }
@ -317,8 +309,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
final char[] array = { 'A', '2', '_', 'D' }; final char[] array = { 'A', '2', '_', 'D' };
assertEquals(baseStr + "[chars={A,2,_,D}]", new ToStringBuilder(base).append("chars", array).toString()); assertEquals(baseStr + "[chars={A,2,_,D}]", new ToStringBuilder(base).append("chars", array).toString());
assertEquals(baseStr + "[letters={A,2,_,D}]", new ToStringBuilder(base).append("letters", array).toString()); assertEquals(baseStr + "[letters={A,2,_,D}]", new ToStringBuilder(base).append("letters", array).toString());
assertEquals(baseStr + "[flags=<null>]", assertEquals(baseStr + "[flags=<null>]", new ToStringBuilder(base).append("flags", (boolean[]) null).toString());
new ToStringBuilder(base).append("flags", (boolean[]) null).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString());
assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append(null, array).toString()); assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append(null, array).toString());
} }
@ -327,10 +318,8 @@ public class ToStringBuilderTest extends AbstractLangTest {
public void testAppendCharArrayWithFieldNameAndFullDetail() { public void testAppendCharArrayWithFieldNameAndFullDetail() {
final char[] array = { 'A', '2', '_', 'D' }; final char[] array = { 'A', '2', '_', 'D' };
assertEquals(baseStr + "[chars={A,2,_,D}]", new ToStringBuilder(base).append("chars", array, true).toString()); assertEquals(baseStr + "[chars={A,2,_,D}]", new ToStringBuilder(base).append("chars", array, true).toString());
assertEquals(baseStr + "[letters=<size=4>]", assertEquals(baseStr + "[letters=<size=4>]", new ToStringBuilder(base).append("letters", array, false).toString());
new ToStringBuilder(base).append("letters", array, false).toString()); assertEquals(baseStr + "[flags=<null>]", new ToStringBuilder(base).append("flags", (boolean[]) null, true).toString());
assertEquals(baseStr + "[flags=<null>]",
new ToStringBuilder(base).append("flags", (boolean[]) null, true).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString());
assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString()); assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString());
} }
@ -338,10 +327,8 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendDoubleArrayWithFieldName() { public void testAppendDoubleArrayWithFieldName() {
final double[] array = { 1.0, 2.9876, -3.00001, 4.3 }; final double[] array = { 1.0, 2.9876, -3.00001, 4.3 };
assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]", assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append("values", array).toString());
new ToStringBuilder(base).append("values", array).toString()); assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null).toString());
assertEquals(baseStr + "[values=<null>]",
new ToStringBuilder(base).append("values", (boolean[]) null).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString());
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(null, array).toString()); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(null, array).toString());
} }
@ -349,12 +336,9 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendDoubleArrayWithFieldNameAndFullDetail() { public void testAppendDoubleArrayWithFieldNameAndFullDetail() {
final double[] array = { 1.0, 2.9876, -3.00001, 4.3 }; final double[] array = { 1.0, 2.9876, -3.00001, 4.3 };
assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]", assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append("values", array, true).toString());
new ToStringBuilder(base).append("values", array, true).toString()); assertEquals(baseStr + "[length=<size=4>]", new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[length=<size=4>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[values=<null>]",
new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString());
assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString()); assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString());
} }
@ -362,10 +346,8 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendFloatArrayWithFieldName() { public void testAppendFloatArrayWithFieldName() {
final float[] array = { 1.0f, 2.9876f, -3.00001f, 4.3f }; final float[] array = { 1.0f, 2.9876f, -3.00001f, 4.3f };
assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]", assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append("values", array).toString());
new ToStringBuilder(base).append("values", array).toString()); assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null).toString());
assertEquals(baseStr + "[values=<null>]",
new ToStringBuilder(base).append("values", (boolean[]) null).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString());
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(null, array).toString()); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(null, array).toString());
} }
@ -373,12 +355,9 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendFloatArrayWithFieldNameAndFullDetail() { public void testAppendFloatArrayWithFieldNameAndFullDetail() {
final float[] array = { 1.0f, 2.9876f, -3.00001f, 4.3f }; final float[] array = { 1.0f, 2.9876f, -3.00001f, 4.3f };
assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]", assertEquals(baseStr + "[values={1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append("values", array, true).toString());
new ToStringBuilder(base).append("values", array, true).toString()); assertEquals(baseStr + "[length=<size=4>]", new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[length=<size=4>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[values=<null>]",
new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString());
assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString()); assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString());
} }
@ -387,8 +366,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
public void testAppendIntArrayWithFieldName() { public void testAppendIntArrayWithFieldName() {
final int[] array = { 1, 2, -3, 4 }; final int[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString()); assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString());
assertEquals(baseStr + "[values=<null>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null).toString());
new ToStringBuilder(base).append("values", (boolean[]) null).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(null, array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(null, array).toString());
} }
@ -396,35 +374,28 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendIntArrayWithFieldNameAndFullDetail() { public void testAppendIntArrayWithFieldNameAndFullDetail() {
final int[] array = { 1, 2, -3, 4 }; final int[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[values={1,2,-3,4}]", assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array, true).toString());
new ToStringBuilder(base).append("values", array, true).toString()); assertEquals(baseStr + "[length=<size=4>]", new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[length=<size=4>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[values=<null>]",
new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString());
assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString()); assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString());
} }
@Test @Test
public void testAppendLongArrayWithFieldName() { public void testAppendLongArrayWithFieldName() {
final long[] array = { 1, 2, -3, 4 }; final long[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString()); assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString());
assertEquals(baseStr + "[values=<null>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null).toString());
new ToStringBuilder(base).append("values", (boolean[]) null).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(null, array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(null, array).toString());
} }
@Test @Test
public void testAppendLongArrayWithFieldNameAndFullDetail() { public void testAppendLongArrayWithFieldNameAndFullDetail() {
final long[] array = { 1, 2, -3, 4 }; final long[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[values={1,2,-3,4}]", assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array, true).toString());
new ToStringBuilder(base).append("values", array, true).toString()); assertEquals(baseStr + "[length=<size=4>]", new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[length=<size=4>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[values=<null>]",
new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString());
assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString()); assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString());
} }
@ -432,25 +403,20 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendObjectArrayWithFieldName() { public void testAppendObjectArrayWithFieldName() {
final Object[] array = { null, base, new int[] { 3, 6 } }; final Object[] array = { null, base, new int[] { 3, 6 } };
assertEquals(baseStr + "[values={<null>,5,{3,6}}]", assertEquals(baseStr + "[values={<null>,5,{3,6}}]", new ToStringBuilder(base).append("values", array).toString());
new ToStringBuilder(base).append("values", array).toString()); assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null).toString());
assertEquals(baseStr + "[values=<null>]",
new ToStringBuilder(base).append("values", (boolean[]) null).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString());
assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(null, array).toString()); assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(null, array).toString());
} }
@Test @Test
public void testAppendObjectArrayWithFieldNameAndFullDetail() { public void testAppendObjectArrayWithFieldNameAndFullDetail() {
final Object[] array = { null, base, new int[] { 3, 6 } }; final Object[] array = { null, base, new int[] { 3, 6 } };
assertEquals(baseStr + "[values={<null>,5,{3,6}}]", assertEquals(baseStr + "[values={<null>,5,{3,6}}]", new ToStringBuilder(base).append("values", array, true).toString());
new ToStringBuilder(base).append("values", array, true).toString()); assertEquals(baseStr + "[length=<size=3>]", new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[length=<size=3>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
new ToStringBuilder(base).append("length", array, false).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString());
assertEquals(baseStr + "[values=<null>]", assertEquals(baseStr + "[<size=3>]", new ToStringBuilder(base).append(null, array, false).toString());
new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString());
assertEquals(baseStr + "[<size=3>]", new ToStringBuilder(base).append(null, array, false).toString());
} }
// Reflection cycle tests // Reflection cycle tests
@ -459,8 +425,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
public void testAppendShortArrayWithFieldName() { public void testAppendShortArrayWithFieldName() {
final short[] array = { 1, 2, -3, 4 }; final short[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString()); assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array).toString());
assertEquals(baseStr + "[values=<null>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null).toString());
new ToStringBuilder(base).append("values", (boolean[]) null).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(null, array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(null, array).toString());
} }
@ -468,12 +433,9 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendShortArrayWithFieldNameAndFullDetail() { public void testAppendShortArrayWithFieldNameAndFullDetail() {
final short[] array = { 1, 2, -3, 4 }; final short[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[values={1,2,-3,4}]", assertEquals(baseStr + "[values={1,2,-3,4}]", new ToStringBuilder(base).append("values", array, true).toString());
new ToStringBuilder(base).append("values", array, true).toString()); assertEquals(baseStr + "[length=<size=4>]", new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[length=<size=4>]", assertEquals(baseStr + "[values=<null>]", new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
new ToStringBuilder(base).append("length", array, false).toString());
assertEquals(baseStr + "[values=<null>]",
new ToStringBuilder(base).append("values", (boolean[]) null, true).toString());
assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString()); assertEquals(baseStr + "[<null>]", new ToStringBuilder(base).append(null, (boolean[]) null, false).toString());
assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString()); assertEquals(baseStr + "[<size=4>]", new ToStringBuilder(base).append(null, array, false).toString());
} }
@ -501,8 +463,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testAppendToStringUsingMultiLineStyle() { public void testAppendToStringUsingMultiLineStyle() {
final MultiLineTestObject obj = new MultiLineTestObject(); final MultiLineTestObject obj = new MultiLineTestObject();
final ToStringBuilder testBuilder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) final ToStringBuilder testBuilder = new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE).appendToString(obj.toString());
.appendToString(obj.toString());
assertEquals(-1, testBuilder.toString().indexOf("testInt=31337")); assertEquals(-1, testBuilder.toString().indexOf("testInt=31337"));
} }
@ -520,7 +481,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testBooleanArray() { public void testBooleanArray() {
boolean[] array = {true, false, false}; boolean[] array = { true, false, false };
assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{true,false,false}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -530,7 +491,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testBooleanArrayArray() { public void testBooleanArrayArray() {
boolean[][] array = {{true, false}, null, {false}}; boolean[][] array = { { true, false }, null, { false } };
assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{{true,false},<null>,{false}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -547,7 +508,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testByteArray() { public void testByteArray() {
byte[] array = {1, 2, -3, 4}; byte[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -557,7 +518,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testByteArrayArray() { public void testByteArrayArray() {
byte[][] array = {{1, 2}, null, {5}}; byte[][] array = { { 1, 2 }, null, { 5 } };
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -574,7 +535,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testCharArray() { public void testCharArray() {
char[] array = {'A', '2', '_', 'D'}; char[] array = { 'A', '2', '_', 'D' };
assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{A,2,_,D}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -584,7 +545,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testCharArrayArray() { public void testCharArrayArray() {
char[][] array = {{'A', 'B'}, null, {'p'}}; char[][] array = { { 'A', 'B' }, null, { 'p' } };
assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{{A,B},<null>,{p}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -631,7 +592,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testDoubleArray() { public void testDoubleArray() {
double[] array = {1.0, 2.9876, -3.00001, 4.3}; double[] array = { 1.0, 2.9876, -3.00001, 4.3 };
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -641,7 +602,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testDoubleArrayArray() { public void testDoubleArrayArray() {
double[][] array = {{1.0, 2.29686}, null, {Double.NaN}}; double[][] array = { { 1.0, 2.29686 }, null, { Double.NaN } };
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -658,7 +619,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testFloatArray() { public void testFloatArray() {
float[] array = {1.0f, 2.9876f, -3.00001f, 4.3f}; float[] array = { 1.0f, 2.9876f, -3.00001f, 4.3f };
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{1.0,2.9876,-3.00001,4.3}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -668,7 +629,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testFloatArrayArray() { public void testFloatArrayArray() {
float[][] array = {{1.0f, 2.29686f}, null, {Float.NaN}}; float[][] array = { { 1.0f, 2.29686f }, null, { Float.NaN } };
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{{1.0,2.29686},<null>,{NaN}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -693,18 +654,14 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testInheritedReflectionStatics() { public void testInheritedReflectionStatics() {
final InheritedReflectionStaticFieldsFixture instance1 = new InheritedReflectionStaticFieldsFixture(); final InheritedReflectionStaticFieldsFixture instance1 = new InheritedReflectionStaticFieldsFixture();
assertEquals( assertEquals(this.toBaseString(instance1) + "[staticInt2=67890,staticString2=staticString2]",
this.toBaseString(instance1) + "[staticInt2=67890,staticString2=staticString2]", ReflectionToStringBuilder.toString(instance1, null, false, true, InheritedReflectionStaticFieldsFixture.class));
ReflectionToStringBuilder.toString(instance1, null, false, true, InheritedReflectionStaticFieldsFixture.class)); assertEquals(this.toBaseString(instance1) + "[staticInt2=67890,staticString2=staticString2,staticInt=12345,staticString=staticString]",
assertEquals( ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class));
this.toBaseString(instance1) + "[staticInt2=67890,staticString2=staticString2,staticInt=12345,staticString=staticString]", assertEquals(this.toBaseString(instance1) + "[staticInt2=67890,staticString2=staticString2,staticInt=12345,staticString=staticString]",
ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class)); this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
assertEquals( assertEquals(this.toBaseString(instance1) + "[staticInt2=67890,staticString2=staticString2,staticInt=12345,staticString=staticString]",
this.toBaseString(instance1) + "[staticInt2=67890,staticString2=staticString2,staticInt=12345,staticString=staticString]", this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticInt2=67890,staticString2=staticString2,staticInt=12345,staticString=staticString]",
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
} }
@Test @Test
@ -722,7 +679,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testIntArray() { public void testIntArray() {
int[] array = {1, 2, -3, 4}; int[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -732,7 +689,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testIntArrayArray() { public void testIntArrayArray() {
int[][] array = {{1, 2}, null, {5}}; int[][] array = { { 1, 2 }, null, { 5 } };
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -749,7 +706,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testLongArray() { public void testLongArray() {
long[] array = {1, 2, -3, 4}; long[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -759,7 +716,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testLongArrayArray() { public void testLongArrayArray() {
long[][] array = {{1, 2}, null, {5}}; long[][] array = { { 1, 2 }, null, { 5 } };
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -787,7 +744,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testObjectArray() { public void testObjectArray() {
Object[] array = {null, base, new int[] {3, 6}}; Object[] array = { null, base, new int[] { 3, 6 } };
assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{<null>,5,{3,6}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -825,29 +782,16 @@ public class ToStringBuilderTest extends AbstractLangTest {
} }
/** /**
* Test a nasty combination of arrays and Objects pointing to each other. * Test a nasty combination of arrays and Objects pointing to each other. objects[0] -&gt; SimpleReflectionTestFixture[ o -&gt; objects ]
* objects[0] -&gt; SimpleReflectionTestFixture[ o -&gt; objects ]
*/ */
@Test @Test
public void testReflectionArrayAndObjectCycle() { public void testReflectionArrayAndObjectCycle() {
final Object[] objects = new Object[1]; final Object[] objects = new Object[1];
final SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(objects); final SimpleReflectionTestFixture simple = new SimpleReflectionTestFixture(objects);
objects[0] = simple; objects[0] = simple;
assertEquals( assertEquals(this.toBaseString(objects) + "[{" + this.toBaseString(simple) + "[o=" + this.toBaseString(objects) + "]" + "}]",
this.toBaseString(objects) ToStringBuilder.reflectionToString(objects));
+ "[{" assertEquals(this.toBaseString(simple) + "[o={" + this.toBaseString(simple) + "}]", ToStringBuilder.reflectionToString(simple));
+ this.toBaseString(simple)
+ "[o="
+ this.toBaseString(objects)
+ "]"
+ "}]",
ToStringBuilder.reflectionToString(objects));
assertEquals(
this.toBaseString(simple)
+ "[o={"
+ this.toBaseString(simple)
+ "}]",
ToStringBuilder.reflectionToString(simple));
} }
@Test @Test
@ -858,18 +802,8 @@ public class ToStringBuilderTest extends AbstractLangTest {
objects[1][0] = objects; objects[1][0] = objects;
objects[1][1] = objects; objects[1][1] = objects;
final String basicToString = this.toBaseString(objects); final String basicToString = this.toBaseString(objects);
assertEquals( assertEquals(basicToString + "[{{" + basicToString + "," + basicToString + "},{" + basicToString + "," + basicToString + "}}]",
basicToString ToStringBuilder.reflectionToString(objects));
+ "[{{"
+ basicToString
+ ","
+ basicToString
+ "},{"
+ basicToString
+ ","
+ basicToString
+ "}}]",
ToStringBuilder.reflectionToString(objects));
} }
/** /**
@ -879,9 +813,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
public void testReflectionArrayCycle() { public void testReflectionArrayCycle() {
final Object[] objects = new Object[1]; final Object[] objects = new Object[1];
objects[0] = objects; objects[0] = objects;
assertEquals( assertEquals(this.toBaseString(objects) + "[{" + this.toBaseString(objects) + "}]", ToStringBuilder.reflectionToString(objects));
this.toBaseString(objects) + "[{" + this.toBaseString(objects) + "}]",
ToStringBuilder.reflectionToString(objects));
} }
/** /**
@ -893,12 +825,8 @@ public class ToStringBuilderTest extends AbstractLangTest {
final Object[] objectsLevel2 = new Object[1]; final Object[] objectsLevel2 = new Object[1];
objects[0] = objectsLevel2; objects[0] = objectsLevel2;
objectsLevel2[0] = objects; objectsLevel2[0] = objects;
assertEquals( assertEquals(this.toBaseString(objects) + "[{{" + this.toBaseString(objects) + "}}]", ToStringBuilder.reflectionToString(objects));
this.toBaseString(objects) + "[{{" + this.toBaseString(objects) + "}}]", assertEquals(this.toBaseString(objectsLevel2) + "[{{" + this.toBaseString(objectsLevel2) + "}}]", ToStringBuilder.reflectionToString(objectsLevel2));
ToStringBuilder.reflectionToString(objects));
assertEquals(
this.toBaseString(objectsLevel2) + "[{{" + this.toBaseString(objectsLevel2) + "}}]",
ToStringBuilder.reflectionToString(objectsLevel2));
} }
/** /**
@ -1044,7 +972,8 @@ public class ToStringBuilderTest extends AbstractLangTest {
// LANG-1337 without this, the generated string can differ depending on the JVM version/vendor // LANG-1337 without this, the generated string can differ depending on the JVM version/vendor
final List<Object> list = new ArrayList<>(ARRAYLIST_INITIAL_CAPACITY); final List<Object> list = new ArrayList<>(ARRAYLIST_INITIAL_CAPACITY);
final String baseString = this.toBaseString(list); final String baseString = this.toBaseString(list);
final String expectedWithTransients = baseString + "[elementData={<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>},size=0,modCount=0]"; final String expectedWithTransients = baseString
+ "[elementData={<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>},size=0,modCount=0]";
final String toStringWithTransients = ToStringBuilder.reflectionToString(list, null, true); final String toStringWithTransients = ToStringBuilder.reflectionToString(list, null, true);
if (!expectedWithTransients.equals(toStringWithTransients)) { if (!expectedWithTransients.equals(toStringWithTransients)) {
assertEquals(expectedWithTransients, toStringWithTransients); assertEquals(expectedWithTransients, toStringWithTransients);
@ -1123,9 +1052,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
final ReflectionTestCycleB b = new ReflectionTestCycleB(); final ReflectionTestCycleB b = new ReflectionTestCycleB();
a.b = b; a.b = b;
b.a = a; b.a = a;
assertEquals( assertEquals(this.toBaseString(a) + "[b=" + this.toBaseString(b) + "[a=" + this.toBaseString(a) + "]]", a.toString());
this.toBaseString(a) + "[b=" + this.toBaseString(b) + "[a=" + this.toBaseString(a) + "]]",
a.toString());
} }
@Test @Test
@ -1152,28 +1079,26 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testReflectionStatics() { public void testReflectionStatics() {
final ReflectionStaticFieldsFixture instance1 = new ReflectionStaticFieldsFixture(); final ReflectionStaticFieldsFixture instance1 = new ReflectionStaticFieldsFixture();
assertEquals( assertEquals(this.toBaseString(instance1) + "[instanceInt=67890,instanceString=instanceString,staticInt=12345,staticString=staticString]",
this.toBaseString(instance1) + "[instanceInt=67890,instanceString=instanceString,staticInt=12345,staticString=staticString]", ReflectionToStringBuilder.toString(instance1, null, false, true, ReflectionStaticFieldsFixture.class));
ReflectionToStringBuilder.toString(instance1, null, false, true, ReflectionStaticFieldsFixture.class)); assertEquals(this.toBaseString(instance1)
assertEquals( + "[instanceInt=67890,instanceString=instanceString,staticInt=12345,staticString=staticString,staticTransientInt=54321,staticTransientString=staticTransientString,transientInt=98765,transientString=transientString]",
this.toBaseString(instance1) + "[instanceInt=67890,instanceString=instanceString,staticInt=12345,staticString=staticString,staticTransientInt=54321,staticTransientString=staticTransientString,transientInt=98765,transientString=transientString]", ReflectionToStringBuilder.toString(instance1, null, true, true, ReflectionStaticFieldsFixture.class));
ReflectionToStringBuilder.toString(instance1, null, true, true, ReflectionStaticFieldsFixture.class)); assertEquals(this.toBaseString(instance1) + "[instanceInt=67890,instanceString=instanceString,staticInt=12345,staticString=staticString]",
assertEquals( this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class));
this.toBaseString(instance1) + "[instanceInt=67890,instanceString=instanceString,staticInt=12345,staticString=staticString]", assertEquals(this.toBaseString(instance1) + "[instanceInt=67890,instanceString=instanceString,staticInt=12345,staticString=staticString]",
this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class)); this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[instanceInt=67890,instanceString=instanceString,staticInt=12345,staticString=staticString]",
this.toStringWithStatics(instance1, null, ReflectionStaticFieldsFixture.class));
} }
/** /**
* Test a class that defines an ivar pointing to itself. This test was * Test a class that defines an ivar pointing to itself. This test was created to show that handling cyclical object resulted in a missing endFieldSeparator
* created to show that handling cyclical object resulted in a missing endFieldSeparator call. * call.
*/ */
@Test @Test
public void testSelfInstanceTwoVarsReflectionObjectCycle() { public void testSelfInstanceTwoVarsReflectionObjectCycle() {
final SelfInstanceTwoVarsReflectionTestFixture test = new SelfInstanceTwoVarsReflectionTestFixture(); final SelfInstanceTwoVarsReflectionTestFixture test = new SelfInstanceTwoVarsReflectionTestFixture();
assertEquals(this.toBaseString(test) + "[otherType=" + test.getOtherType().toString() + ",typeIsSelf=" + this.toBaseString(test) + "]", test.toString()); assertEquals(this.toBaseString(test) + "[otherType=" + test.getOtherType().toString() + ",typeIsSelf=" + this.toBaseString(test) + "]",
test.toString());
} }
/** /**
@ -1199,7 +1124,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testShortArray() { public void testShortArray() {
short[] array = {1, 2, -3, 4}; short[] array = { 1, 2, -3, 4 };
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{1,2,-3,4}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -1209,7 +1134,7 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testShortArrayArray() { public void testShortArrayArray() {
short[][] array = {{1, 2}, null, {5}}; short[][] array = { { 1, 2 }, null, { 5 } };
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append(array).toString());
assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString()); assertEquals(baseStr + "[{{1,2},<null>,{5}}]", new ToStringBuilder(base).append((Object) array).toString());
array = null; array = null;
@ -1230,22 +1155,19 @@ public class ToStringBuilderTest extends AbstractLangTest {
@Test @Test
public void testSimpleReflectionStatics() { public void testSimpleReflectionStatics() {
final SimpleReflectionStaticFieldsFixture instance1 = new SimpleReflectionStaticFieldsFixture(); final SimpleReflectionStaticFieldsFixture instance1 = new SimpleReflectionStaticFieldsFixture();
assertEquals( assertEquals(this.toBaseString(instance1) + "[staticInt=12345,staticString=staticString]",
this.toBaseString(instance1) + "[staticInt=12345,staticString=staticString]", ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class));
ReflectionToStringBuilder.toString(instance1, null, false, true, SimpleReflectionStaticFieldsFixture.class)); assertEquals(this.toBaseString(instance1) + "[staticInt=12345,staticString=staticString]",
assertEquals( ReflectionToStringBuilder.toString(instance1, null, true, true, SimpleReflectionStaticFieldsFixture.class));
this.toBaseString(instance1) + "[staticInt=12345,staticString=staticString]", assertEquals(this.toBaseString(instance1) + "[staticInt=12345,staticString=staticString]",
ReflectionToStringBuilder.toString(instance1, null, true, true, SimpleReflectionStaticFieldsFixture.class)); this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
assertEquals( assertEquals(this.toBaseString(instance1) + "[staticInt=12345,staticString=staticString]",
this.toBaseString(instance1) + "[staticInt=12345,staticString=staticString]", this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
assertEquals(
this.toBaseString(instance1) + "[staticInt=12345,staticString=staticString]",
this.toStringWithStatics(instance1, null, SimpleReflectionStaticFieldsFixture.class));
} }
/** /**
* Create the same toString() as Object.toString(). * Create the same toString() as Object.toString().
*
* @param o the object to create the string for. * @param o the object to create the string for.
* @return a String in the Object.toString format. * @return a String in the Object.toString format.
*/ */
@ -1254,28 +1176,25 @@ public class ToStringBuilderTest extends AbstractLangTest {
} }
/** /**
* <p>This method uses reflection to build a suitable * This method uses reflection to build a suitable {@code toString} value which includes static fields.
* {@code toString} value which includes static fields.</p> * <p>
* It uses {@code AccessibleObject.setAccessible} to gain access to private fields. This means that it will throw a security exception if run under a
* security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.
* </p>
* <p>
* Transient fields are not output.
* </p>
* <p>
* Superclass fields will be appended up to and including the specified superclass. A null superclass is treated as {@link Object}.
* </p>
* <p>
* If the style is {@code null}, the default {@code ToStringStyle} is used.
* </p>
* *
* <p>It uses {@code AccessibleObject.setAccessible} to gain access to private * @param <T> the type of the output object
* fields. This means that it will throw a security exception if run * @param object the Object to be output
* under a security manager, if the permissions are not set up correctly. * @param style the style of the {@code toString} to create, may be {@code null}
* It is also not as efficient as testing explicitly.</p> * @param reflectUpToClass the superclass to reflect up to (inclusive), may be {@code null}
*
* <p>Transient fields are not output.</p>
*
* <p>Superclass fields will be appended up to and including the specified superclass.
* A null superclass is treated as {@link Object}.</p>
*
* <p>If the style is {@code null}, the default
* {@code ToStringStyle} is used.</p>
*
* @param <T> the type of the output object
* @param object the Object to be output
* @param style the style of the {@code toString} to create,
* may be {@code null}
* @param reflectUpToClass the superclass to reflect up to (inclusive),
* may be {@code null}
* @return the String result * @return the String result
* @throws IllegalArgumentException if the Object is {@code null} * @throws IllegalArgumentException if the Object is {@code null}
*/ */

View File

@ -32,7 +32,7 @@ import org.junit.jupiter.api.Test;
*/ */
public class FractionTest extends AbstractLangTest { public class FractionTest extends AbstractLangTest {
private static final int SKIP = 500; //53 private static final int SKIP = 500; // 53
@Test @Test
public void testAbs() { public void testAbs() {
@ -116,17 +116,17 @@ public class FractionTest extends AbstractLangTest {
f = f2.add(f1); f = f2.add(f1);
assertSame(f2, f); assertSame(f2, f);
f1 = Fraction.getFraction(-1, 13*13*2*2); f1 = Fraction.getFraction(-1, 13 * 13 * 2 * 2);
f2 = Fraction.getFraction(-2, 13*17*2); f2 = Fraction.getFraction(-2, 13 * 17 * 2);
final Fraction fr = f1.add(f2); final Fraction fr = f1.add(f2);
assertEquals(13*13*17*2*2, fr.getDenominator()); assertEquals(13 * 13 * 17 * 2 * 2, fr.getDenominator());
assertEquals(-17 - 2*13*2, fr.getNumerator()); assertEquals(-17 - 2 * 13 * 2, fr.getNumerator());
assertThrows(NullPointerException.class, () -> fr.add(null)); assertThrows(NullPointerException.class, () -> fr.add(null));
// if this fraction is added naively, it will overflow. // if this fraction is added naively, it will overflow.
// check that it doesn't. // check that it doesn't.
f1 = Fraction.getFraction(1, 32768*3); f1 = Fraction.getFraction(1, 32768 * 3);
f2 = Fraction.getFraction(1, 59049); f2 = Fraction.getFraction(1, 59049);
f = f1.add(f2); f = f1.add(f2);
assertEquals(52451, f.getNumerator()); assertEquals(52451, f.getNumerator());
@ -135,7 +135,7 @@ public class FractionTest extends AbstractLangTest {
f1 = Fraction.getFraction(Integer.MIN_VALUE, 3); f1 = Fraction.getFraction(Integer.MIN_VALUE, 3);
f2 = Fraction.ONE_THIRD; f2 = Fraction.ONE_THIRD;
f = f1.add(f2); f = f1.add(f2);
assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(Integer.MIN_VALUE + 1, f.getNumerator());
assertEquals(3, f.getDenominator()); assertEquals(3, f.getDenominator());
f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1); f1 = Fraction.getFraction(Integer.MAX_VALUE - 1, 1);
@ -148,9 +148,7 @@ public class FractionTest extends AbstractLangTest {
assertThrows(ArithmeticException.class, () -> overflower.add(Fraction.ONE)); // should overflow assertThrows(ArithmeticException.class, () -> overflower.add(Fraction.ONE)); // should overflow
// denominator should not be a multiple of 2 or 3 to trigger overflow // denominator should not be a multiple of 2 or 3 to trigger overflow
assertThrows( assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 5).add(Fraction.getFraction(-1, 5)));
ArithmeticException.class,
() -> Fraction.getFraction(Integer.MIN_VALUE, 5).add(Fraction.getFraction(-1, 5)));
final Fraction maxValue = Fraction.getFraction(-Integer.MAX_VALUE, 1); final Fraction maxValue = Fraction.getFraction(-Integer.MAX_VALUE, 1);
assertThrows(ArithmeticException.class, () -> maxValue.add(maxValue)); assertThrows(ArithmeticException.class, () -> maxValue.add(maxValue));
@ -352,14 +350,14 @@ public class FractionTest extends AbstractLangTest {
assertEquals(3, f.getDenominator()); assertEquals(3, f.getDenominator());
// small // small
f = Fraction.getFraction(1.0d/10001d); f = Fraction.getFraction(1.0d / 10001d);
assertEquals(0, f.getNumerator()); assertEquals(0, f.getNumerator());
assertEquals(1, f.getDenominator()); assertEquals(1, f.getDenominator());
// normal // normal
Fraction f2; Fraction f2;
for (int i = 1; i <= 100; i++) { // denominator for (int i = 1; i <= 100; i++) { // denominator
for (int j = 1; j <= i; j++) { // numerator for (int j = 1; j <= i; j++) { // numerator
f = Fraction.getFraction((double) j / (double) i); f = Fraction.getFraction((double) j / (double) i);
f2 = Fraction.getReducedFraction(j, i); f2 = Fraction.getReducedFraction(j, i);
@ -367,9 +365,9 @@ public class FractionTest extends AbstractLangTest {
assertEquals(f2.getDenominator(), f.getDenominator()); assertEquals(f2.getDenominator(), f.getDenominator());
} }
} }
// save time by skipping some tests! ( // save time by skipping some tests! (
for (int i = 1001; i <= 10000; i+=SKIP) { // denominator for (int i = 1001; i <= 10000; i += SKIP) { // denominator
for (int j = 1; j <= i; j++) { // numerator for (int j = 1; j <= i; j++) { // numerator
f = Fraction.getFraction((double) j / (double) i); f = Fraction.getFraction((double) j / (double) i);
f2 = Fraction.getReducedFraction(j, i); f2 = Fraction.getReducedFraction(j, i);
assertEquals(f2.getNumerator(), f.getNumerator()); assertEquals(f2.getNumerator(), f.getNumerator());
@ -726,9 +724,9 @@ public class FractionTest extends AbstractLangTest {
assertEquals(75, f.getDenominator()); assertEquals(75, f.getDenominator());
// large values // large values
f = Fraction.getFraction(Integer.MAX_VALUE-1, Integer.MAX_VALUE); f = Fraction.getFraction(Integer.MAX_VALUE - 1, Integer.MAX_VALUE);
f = f.negate(); f = f.negate();
assertEquals(Integer.MIN_VALUE+2, f.getNumerator()); assertEquals(Integer.MIN_VALUE + 2, f.getNumerator());
assertEquals(Integer.MAX_VALUE, f.getDenominator()); assertEquals(Integer.MAX_VALUE, f.getDenominator());
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).negate()); assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).negate());
@ -1014,7 +1012,7 @@ public class FractionTest extends AbstractLangTest {
// if this fraction is subtracted naively, it will overflow. // if this fraction is subtracted naively, it will overflow.
// check that it doesn't. // check that it doesn't.
f1 = Fraction.getFraction(1, 32768*3); f1 = Fraction.getFraction(1, 32768 * 3);
f2 = Fraction.getFraction(1, 59049); f2 = Fraction.getFraction(1, 59049);
f = f1.subtract(f2); f = f1.subtract(f2);
assertEquals(-13085, f.getNumerator()); assertEquals(-13085, f.getNumerator());
@ -1023,36 +1021,27 @@ public class FractionTest extends AbstractLangTest {
f1 = Fraction.getFraction(Integer.MIN_VALUE, 3); f1 = Fraction.getFraction(Integer.MIN_VALUE, 3);
f2 = Fraction.ONE_THIRD.negate(); f2 = Fraction.ONE_THIRD.negate();
f = f1.subtract(f2); f = f1.subtract(f2);
assertEquals(Integer.MIN_VALUE+1, f.getNumerator()); assertEquals(Integer.MIN_VALUE + 1, f.getNumerator());
assertEquals(3, f.getDenominator()); assertEquals(3, f.getDenominator());
f1 = Fraction.getFraction(Integer.MAX_VALUE, 1); f1 = Fraction.getFraction(Integer.MAX_VALUE, 1);
f2 = Fraction.ONE; f2 = Fraction.ONE;
f = f1.subtract(f2); f = f1.subtract(f2);
assertEquals(Integer.MAX_VALUE-1, f.getNumerator()); assertEquals(Integer.MAX_VALUE - 1, f.getNumerator());
assertEquals(1, f.getDenominator()); assertEquals(1, f.getDenominator());
// Should overflow // Should overflow
assertThrows( assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, Integer.MAX_VALUE).subtract(Fraction.getFraction(1, Integer.MAX_VALUE - 1)));
ArithmeticException.class,
() -> Fraction.getFraction(1, Integer.MAX_VALUE).subtract(Fraction.getFraction(1, Integer.MAX_VALUE - 1)));
// denominator should not be a multiple of 2 or 3 to trigger overflow // denominator should not be a multiple of 2 or 3 to trigger overflow
assertThrows( assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 5).subtract(Fraction.getFraction(1, 5)));
ArithmeticException.class,
() -> Fraction.getFraction(Integer.MIN_VALUE, 5).subtract(Fraction.getFraction(1, 5)));
assertThrows( assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).subtract(Fraction.ONE));
ArithmeticException.class, () -> Fraction.getFraction(Integer.MIN_VALUE, 1).subtract(Fraction.ONE));
assertThrows( assertThrows(ArithmeticException.class, () -> Fraction.getFraction(Integer.MAX_VALUE, 1).subtract(Fraction.ONE.negate()));
ArithmeticException.class,
() -> Fraction.getFraction(Integer.MAX_VALUE, 1).subtract(Fraction.ONE.negate()));
// Should overflow // Should overflow
assertThrows( assertThrows(ArithmeticException.class, () -> Fraction.getFraction(3, 327680).subtract(Fraction.getFraction(2, 59049)));
ArithmeticException.class,
() -> Fraction.getFraction(3, 327680).subtract(Fraction.getFraction(2, 59049)));
} }
@Test @Test

View File

@ -38,7 +38,8 @@ import org.junit.jupiter.api.Test;
* Unit tests ConstructorUtils * Unit tests ConstructorUtils
*/ */
public class ConstructorUtilsTest extends AbstractLangTest { public class ConstructorUtilsTest extends AbstractLangTest {
private static class BaseClass {} private static class BaseClass {
}
static class PrivateClass { static class PrivateClass {
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -52,7 +53,8 @@ public class ConstructorUtilsTest extends AbstractLangTest {
} }
} }
private static final class SubClass extends BaseClass {} private static final class SubClass extends BaseClass {
}
public static class TestBean { public static class TestBean {
private final String toString; private final String toString;
@ -117,8 +119,8 @@ public class ConstructorUtilsTest extends AbstractLangTest {
} }
void verify(final String str, final String[] args) { void verify(final String str, final String[] args) {
assertEquals(str, toString); assertEquals(str, toString);
assertArrayEquals(args, varArgs); assertArrayEquals(args, varArgs);
} }
} }
@ -128,10 +130,8 @@ public class ConstructorUtilsTest extends AbstractLangTest {
classCache = new HashMap<>(); classCache = new HashMap<>();
} }
private void expectMatchingAccessibleConstructorParameterTypes(final Class<?> cls, private void expectMatchingAccessibleConstructorParameterTypes(final Class<?> cls, final Class<?>[] requestTypes, final Class<?>[] actualTypes) {
final Class<?>[] requestTypes, final Class<?>[] actualTypes) { final Constructor<?> c = ConstructorUtils.getMatchingAccessibleConstructor(cls, requestTypes);
final Constructor<?> c = ConstructorUtils.getMatchingAccessibleConstructor(cls,
requestTypes);
assertArrayEquals(actualTypes, c.getParameterTypes(), toString(c.getParameterTypes()) + " not equals " + toString(actualTypes)); assertArrayEquals(actualTypes, c.getParameterTypes(), toString(c.getParameterTypes()) + " not equals " + toString(actualTypes));
} }
@ -156,136 +156,86 @@ public class ConstructorUtilsTest extends AbstractLangTest {
@Test @Test
public void testGetAccessibleConstructor() throws Exception { public void testGetAccessibleConstructor() throws Exception {
assertNotNull(ConstructorUtils.getAccessibleConstructor(Object.class assertNotNull(ConstructorUtils.getAccessibleConstructor(Object.class.getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY)));
.getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY))); assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.class.getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY)));
assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.class
.getConstructor(ArrayUtils.EMPTY_CLASS_ARRAY)));
assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.PublicInnerClass.class)); assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.PublicInnerClass.class));
} }
@Test @Test
public void testGetAccessibleConstructorFromDescription() { public void testGetAccessibleConstructorFromDescription() {
assertNotNull(ConstructorUtils.getAccessibleConstructor(Object.class, assertNotNull(ConstructorUtils.getAccessibleConstructor(Object.class, ArrayUtils.EMPTY_CLASS_ARRAY));
ArrayUtils.EMPTY_CLASS_ARRAY)); assertNull(ConstructorUtils.getAccessibleConstructor(PrivateClass.class, ArrayUtils.EMPTY_CLASS_ARRAY));
assertNull(ConstructorUtils.getAccessibleConstructor(
PrivateClass.class, ArrayUtils.EMPTY_CLASS_ARRAY));
} }
@Test @Test
public void testGetMatchingAccessibleMethod() { public void testGetMatchingAccessibleMethod() {
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, expectMatchingAccessibleConstructorParameterTypes(TestBean.class, ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.EMPTY_CLASS_ARRAY);
ArrayUtils.EMPTY_CLASS_ARRAY, ArrayUtils.EMPTY_CLASS_ARRAY); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, null, ArrayUtils.EMPTY_CLASS_ARRAY);
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, null, expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(String.class), singletonArray(String.class));
ArrayUtils.EMPTY_CLASS_ARRAY); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Object.class), singletonArray(Object.class));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Boolean.class), singletonArray(Object.class));
singletonArray(String.class), singletonArray(String.class)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Byte.class), singletonArray(Integer.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Byte.TYPE), singletonArray(Integer.TYPE));
singletonArray(Object.class), singletonArray(Object.class)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Short.class), singletonArray(Integer.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Short.TYPE), singletonArray(Integer.TYPE));
singletonArray(Boolean.class), singletonArray(Object.class)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Character.class), singletonArray(Integer.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Character.TYPE), singletonArray(Integer.TYPE));
singletonArray(Byte.class), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Integer.class), singletonArray(Integer.class));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Integer.TYPE), singletonArray(Integer.TYPE));
singletonArray(Byte.TYPE), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Long.class), singletonArray(Double.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Long.TYPE), singletonArray(Double.TYPE));
singletonArray(Short.class), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Float.class), singletonArray(Double.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Float.TYPE), singletonArray(Double.TYPE));
singletonArray(Short.TYPE), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Double.class), singletonArray(Double.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, expectMatchingAccessibleConstructorParameterTypes(TestBean.class, singletonArray(Double.TYPE), singletonArray(Double.TYPE));
singletonArray(Character.class), singletonArray(Integer.TYPE)); expectMatchingAccessibleConstructorParameterTypes(TestBean.class, new Class<?>[] { SubClass.class, String[].class },
expectMatchingAccessibleConstructorParameterTypes(TestBean.class, new Class<?>[] { BaseClass.class, String[].class });
singletonArray(Character.TYPE), singletonArray(Integer.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class,
singletonArray(Integer.class), singletonArray(Integer.class));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class,
singletonArray(Integer.TYPE), singletonArray(Integer.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class,
singletonArray(Long.class), singletonArray(Double.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class,
singletonArray(Long.TYPE), singletonArray(Double.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class,
singletonArray(Float.class), singletonArray(Double.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class,
singletonArray(Float.TYPE), singletonArray(Double.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class,
singletonArray(Double.class), singletonArray(Double.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class,
singletonArray(Double.TYPE), singletonArray(Double.TYPE));
expectMatchingAccessibleConstructorParameterTypes(TestBean.class,
new Class<?>[]{SubClass.class, String[].class},
new Class<?>[]{BaseClass.class, String[].class});
} }
@Test @Test
public void testInvokeConstructor() throws Exception { public void testInvokeConstructor() throws Exception {
assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class, assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class, (Object[]) ArrayUtils.EMPTY_CLASS_ARRAY).toString());
(Object[]) ArrayUtils.EMPTY_CLASS_ARRAY).toString()); assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class, (Object[]) null).toString());
assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class,
(Object[]) null).toString());
assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class).toString()); assertEquals("()", ConstructorUtils.invokeConstructor(TestBean.class).toString());
assertEquals("(String)", ConstructorUtils.invokeConstructor( assertEquals("(String)", ConstructorUtils.invokeConstructor(TestBean.class, "").toString());
TestBean.class, "").toString()); assertEquals("(Object)", ConstructorUtils.invokeConstructor(TestBean.class, new Object()).toString());
assertEquals("(Object)", ConstructorUtils.invokeConstructor( assertEquals("(Object)", ConstructorUtils.invokeConstructor(TestBean.class, Boolean.TRUE).toString());
TestBean.class, new Object()).toString()); assertEquals("(Integer)", ConstructorUtils.invokeConstructor(TestBean.class, NumberUtils.INTEGER_ONE).toString());
assertEquals("(Object)", ConstructorUtils.invokeConstructor( assertEquals("(int)", ConstructorUtils.invokeConstructor(TestBean.class, NumberUtils.BYTE_ONE).toString());
TestBean.class, Boolean.TRUE).toString()); assertEquals("(double)", ConstructorUtils.invokeConstructor(TestBean.class, NumberUtils.LONG_ONE).toString());
assertEquals("(Integer)", ConstructorUtils.invokeConstructor( assertEquals("(double)", ConstructorUtils.invokeConstructor(TestBean.class, NumberUtils.DOUBLE_ONE).toString());
TestBean.class, NumberUtils.INTEGER_ONE).toString()); ConstructorUtils.invokeConstructor(TestBean.class, NumberUtils.INTEGER_ONE).verify("(Integer)", null);
assertEquals("(int)", ConstructorUtils.invokeConstructor( ConstructorUtils.invokeConstructor(TestBean.class, "a", "b").verify("(String...)", new String[] { "a", "b" });
TestBean.class, NumberUtils.BYTE_ONE).toString()); ConstructorUtils.invokeConstructor(TestBean.class, NumberUtils.INTEGER_ONE, "a", "b").verify("(Integer, String...)", new String[] { "a", "b" });
assertEquals("(double)", ConstructorUtils.invokeConstructor( ConstructorUtils.invokeConstructor(TestBean.class, new SubClass(), new String[] { "a", "b" }).verify("(BaseClass, String...)",
TestBean.class, NumberUtils.LONG_ONE).toString()); new String[] { "a", "b" });
assertEquals("(double)", ConstructorUtils.invokeConstructor(
TestBean.class, NumberUtils.DOUBLE_ONE).toString());
ConstructorUtils.invokeConstructor(TestBean.class, NumberUtils.INTEGER_ONE)
.verify("(Integer)", null);
ConstructorUtils.invokeConstructor(TestBean.class, "a", "b")
.verify("(String...)", new String[]{"a", "b"});
ConstructorUtils.invokeConstructor(TestBean.class, NumberUtils.INTEGER_ONE, "a", "b")
.verify("(Integer, String...)", new String[]{"a", "b"});
ConstructorUtils.invokeConstructor(TestBean.class, new SubClass(), new String[]{"a", "b"})
.verify("(BaseClass, String...)", new String[]{"a", "b"});
} }
@Test @Test
public void testInvokeExactConstructor() throws Exception { public void testInvokeExactConstructor() throws Exception {
assertEquals("()", ConstructorUtils.invokeExactConstructor( assertEquals("()", ConstructorUtils.invokeExactConstructor(TestBean.class, (Object[]) ArrayUtils.EMPTY_CLASS_ARRAY).toString());
TestBean.class, (Object[]) ArrayUtils.EMPTY_CLASS_ARRAY).toString()); assertEquals("()", ConstructorUtils.invokeExactConstructor(TestBean.class, (Object[]) null).toString());
assertEquals("()", ConstructorUtils.invokeExactConstructor( assertEquals("(String)", ConstructorUtils.invokeExactConstructor(TestBean.class, "").toString());
TestBean.class, (Object[]) null).toString()); assertEquals("(Object)", ConstructorUtils.invokeExactConstructor(TestBean.class, new Object()).toString());
assertEquals("(String)", ConstructorUtils.invokeExactConstructor( assertEquals("(Integer)", ConstructorUtils.invokeExactConstructor(TestBean.class, NumberUtils.INTEGER_ONE).toString());
TestBean.class, "").toString()); assertEquals("(double)",
assertEquals("(Object)", ConstructorUtils.invokeExactConstructor( ConstructorUtils.invokeExactConstructor(TestBean.class, new Object[] { NumberUtils.DOUBLE_ONE }, new Class[] { Double.TYPE }).toString());
TestBean.class, new Object()).toString());
assertEquals("(Integer)", ConstructorUtils.invokeExactConstructor(
TestBean.class, NumberUtils.INTEGER_ONE).toString());
assertEquals("(double)", ConstructorUtils.invokeExactConstructor(
TestBean.class, new Object[] { NumberUtils.DOUBLE_ONE },
new Class[] { Double.TYPE }).toString());
assertThrows( assertThrows(NoSuchMethodException.class, () -> ConstructorUtils.invokeExactConstructor(TestBean.class, NumberUtils.BYTE_ONE));
NoSuchMethodException.class, assertThrows(NoSuchMethodException.class, () -> ConstructorUtils.invokeExactConstructor(TestBean.class, NumberUtils.LONG_ONE));
() -> ConstructorUtils.invokeExactConstructor(TestBean.class, NumberUtils.BYTE_ONE)); assertThrows(NoSuchMethodException.class, () -> ConstructorUtils.invokeExactConstructor(TestBean.class, Boolean.TRUE));
assertThrows(
NoSuchMethodException.class,
() -> ConstructorUtils.invokeExactConstructor(TestBean.class, NumberUtils.LONG_ONE));
assertThrows(
NoSuchMethodException.class,
() -> ConstructorUtils.invokeExactConstructor(TestBean.class, Boolean.TRUE));
} }
@Test @Test
public void testNullArgument() { public void testNullArgument() {
expectMatchingAccessibleConstructorParameterTypes(MutableObject.class, expectMatchingAccessibleConstructorParameterTypes(MutableObject.class, singletonArray(null), singletonArray(Object.class));
singletonArray(null), singletonArray(Object.class));
} }
@Test @Test
public void testVarArgsUnboxing() throws Exception { public void testVarArgsUnboxing() throws Exception {
final TestBean testBean = ConstructorUtils.invokeConstructor( final TestBean testBean = ConstructorUtils.invokeConstructor(TestBean.class, Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3));
TestBean.class, Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3));
assertArrayEquals(new String[]{"2", "3"}, testBean.varArgs); assertArrayEquals(new String[] { "2", "3" }, testBean.varArgs);
} }
private String toString(final Class<?>[] c) { private String toString(final Class<?>[] c) {

View File

@ -30,29 +30,39 @@ public class TypeLiteralTest extends AbstractLangTest {
@Test @Test
public void testBasic() { public void testBasic() {
assertTrue(TypeUtils.equals(String.class, new TypeLiteral<String>() {}.value)); assertTrue(TypeUtils.equals(String.class, new TypeLiteral<String>() {
assertTrue(TypeUtils.equals(TypeUtils.parameterize(List.class, String.class), }.value));
new TypeLiteral<List<String>>() {}.value)); assertTrue(TypeUtils.equals(TypeUtils.parameterize(List.class, String.class), new TypeLiteral<List<String>>() {
}.value));
} }
@Test @Test
public void testEquals() { public void testEquals() {
assertEquals(new TypeLiteral<String>() {}, new TypeLiteral<String>() {}); assertEquals(new TypeLiteral<String>() {
assertEquals(new TypeLiteral<List<String>>() {}, new TypeLiteral<List<String>>() {}); }, new TypeLiteral<String>() {
assertNotEquals(new TypeLiteral<String>() {}, new TypeLiteral<List<String>>() {}); });
assertEquals(new TypeLiteral<List<String>>() {
}, new TypeLiteral<List<String>>() {
});
assertNotEquals(new TypeLiteral<String>() {
}, new TypeLiteral<List<String>>() {
});
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
@Test @Test
public void testRaw() { public void testRaw() {
assertThrows(NullPointerException.class, () -> new TypeLiteral() {}); assertThrows(NullPointerException.class, () -> new TypeLiteral() {
});
} }
@Test @Test
public void testTyped() { public void testTyped() {
final Typed<String> stringType = new TypeLiteral<String>() {}; final Typed<String> stringType = new TypeLiteral<String>() {
};
assertTrue(TypeUtils.equals(String.class, stringType.getType())); assertTrue(TypeUtils.equals(String.class, stringType.getType()));
final Typed<List<String>> listOfStringType = new TypeLiteral<List<String>>() {}; final Typed<List<String>> listOfStringType = new TypeLiteral<List<String>>() {
};
assertTrue(TypeUtils.equals(TypeUtils.parameterize(List.class, String.class), listOfStringType.getType())); assertTrue(TypeUtils.equals(TypeUtils.parameterize(List.class, String.class), listOfStringType.getType()));
} }
} }

View File

@ -17,36 +17,36 @@
package org.apache.commons.lang3.test; package org.apache.commons.lang3.test;
/** /**
* Allows for testing an exception that is not visible to * Allows for testing an exception that is not visible to {@link org.apache.commons.lang3.exception.ExceptionUtils}
* {@link org.apache.commons.lang3.exception.ExceptionUtils}
*/ */
public class NotVisibleExceptionFactory { public class NotVisibleExceptionFactory {
private static final class NotVisibleException extends Exception { private static final class NotVisibleException extends Exception {
private static final long serialVersionUID = 1L; // avoid warning private static final long serialVersionUID = 1L; // avoid warning
private final Throwable cause; private final Throwable cause;
private NotVisibleException(final Throwable cause) { private NotVisibleException(final Throwable cause) {
this.cause = cause; this.cause = cause;
}
@Override
public synchronized Throwable getCause() {
return cause;
}
} }
@Override /**
public synchronized Throwable getCause() { * Create a new Exception whose getCause method returns the provided cause.
return cause; *
* @param cause the cause of the exception
* @return a new {@link Exception}
*/
public static Exception createException(final Throwable cause) {
return new NotVisibleException(cause);
} }
}
/** private NotVisibleExceptionFactory() {
* Create a new Exception whose getCause method returns the }
* provided cause.
* @param cause the cause of the exception
* @return a new {@link Exception}
*/
public static Exception createException(final Throwable cause) {
return new NotVisibleException(cause);
}
private NotVisibleExceptionFactory() {}
} }

View File

@ -33,7 +33,7 @@ public class FormattableUtilsTest extends AbstractLangTest {
@Test @Test
public void testAlternatePadCharacter() { public void testAlternatePadCharacter() {
final char pad='_'; final char pad = '_';
assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, pad).toString()); assertEquals("foo", FormattableUtils.append("foo", new Formatter(), 0, -1, -1, pad).toString());
assertEquals("fo", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, pad).toString()); assertEquals("fo", FormattableUtils.append("foo", new Formatter(), 0, -1, 2, pad).toString());
assertEquals("_foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, pad).toString()); assertEquals("_foo", FormattableUtils.append("foo", new Formatter(), 0, 4, -1, pad).toString());

View File

@ -41,30 +41,30 @@ public class EntityArraysTest extends AbstractLangTest {
public void testHTML40_EXTENDED_ESCAPE() { public void testHTML40_EXTENDED_ESCAPE() {
final Set<String> col0 = new HashSet<>(); final Set<String> col0 = new HashSet<>();
final Set<String> col1 = new HashSet<>(); final Set<String> col1 = new HashSet<>();
final String [][] sa = EntityArrays.HTML40_EXTENDED_ESCAPE(); final String[][] sa = EntityArrays.HTML40_EXTENDED_ESCAPE();
for (int i =0; i <sa.length; i++) { for (int i = 0; i < sa.length; i++) {
assertTrue(col0.add(sa[i][0]), "Already added entry 0: "+i+" "+sa[i][0]); assertTrue(col0.add(sa[i][0]), "Already added entry 0: " + i + " " + sa[i][0]);
assertTrue(col1.add(sa[i][1]), "Already added entry 1: "+i+" "+sa[i][1]); assertTrue(col1.add(sa[i][1]), "Already added entry 1: " + i + " " + sa[i][1]);
} }
} }
// LANG-658 - check arrays for duplicate entries // LANG-658 - check arrays for duplicate entries
@Test @Test
public void testISO8859_1_ESCAPE() { public void testISO8859_1_ESCAPE() {
final Set<String> col0 = new HashSet<>(); final Set<String> col0 = new HashSet<>();
final Set<String> col1 = new HashSet<>(); final Set<String> col1 = new HashSet<>();
final String [][] sa = EntityArrays.ISO8859_1_ESCAPE(); final String[][] sa = EntityArrays.ISO8859_1_ESCAPE();
boolean success = true; boolean success = true;
for (int i =0; i <sa.length; i++) { for (int i = 0; i < sa.length; i++) {
final boolean add0 = col0.add(sa[i][0]); final boolean add0 = col0.add(sa[i][0]);
final boolean add1 = col1.add(sa[i][1]); final boolean add1 = col1.add(sa[i][1]);
if (!add0) { if (!add0) {
success = false; success = false;
System.out.println("Already added entry 0: "+i+" "+sa[i][0]+" "+sa[i][1]); System.out.println("Already added entry 0: " + i + " " + sa[i][0] + " " + sa[i][1]);
} }
if (!add1) { if (!add1) {
success = false; success = false;
System.out.println("Already added entry 1: "+i+" "+sa[i][0]+" "+sa[i][1]); System.out.println("Already added entry 1: " + i + " " + sa[i][0] + " " + sa[i][1]);
} }
} }
assertTrue(success, "One or more errors detected"); assertTrue(success, "One or more errors detected");

View File

@ -28,9 +28,9 @@ import org.junit.jupiter.api.Test;
public class DateUtilsFragmentTest extends AbstractLangTest { public class DateUtilsFragmentTest extends AbstractLangTest {
private static final int months = 7; // second final prime before 12 private static final int months = 7; // second final prime before 12
private static final int days = 23; // second final prime before 31 (and valid) private static final int days = 23; // second final prime before 31 (and valid)
private static final int hours = 19; // second final prime before 24 private static final int hours = 19; // second final prime before 24
private static final int minutes = 53; // second final prime before 60 private static final int minutes = 53; // second final prime before 60
private static final int seconds = 47; // third final prime before 60 private static final int seconds = 47; // third final prime before 60
private static final int millis = 991; // second final prime before 1000 private static final int millis = 991; // second final prime before 1000
@ -127,25 +127,19 @@ public class DateUtilsFragmentTest extends AbstractLangTest {
@Test @Test
public void testHoursOfMonthWithCalendar() { public void testHoursOfMonthWithCalendar() {
final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.MONTH); final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.MONTH);
assertEquals( hours +(days - 1) * DateUtils.MILLIS_PER_DAY assertEquals(hours + (days - 1) * DateUtils.MILLIS_PER_DAY / DateUtils.MILLIS_PER_HOUR, testResult);
/ DateUtils.MILLIS_PER_HOUR,
testResult);
} }
@Test @Test
public void testHoursOfMonthWithDate() { public void testHoursOfMonthWithDate() {
final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.MONTH); final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.MONTH);
assertEquals(hours + (days - 1) * DateUtils.MILLIS_PER_DAY assertEquals(hours + (days - 1) * DateUtils.MILLIS_PER_DAY / DateUtils.MILLIS_PER_HOUR, testResult);
/ DateUtils.MILLIS_PER_HOUR,
testResult);
} }
@Test @Test
public void testHoursOfYearWithCalendar() { public void testHoursOfYearWithCalendar() {
final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.YEAR); final long testResult = DateUtils.getFragmentInHours(aCalendar, Calendar.YEAR);
assertEquals( hours +(aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY assertEquals(hours + (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY / DateUtils.MILLIS_PER_HOUR, testResult);
/ DateUtils.MILLIS_PER_HOUR,
testResult);
} }
@Test @Test
@ -153,12 +147,10 @@ public class DateUtilsFragmentTest extends AbstractLangTest {
final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.YEAR); final long testResult = DateUtils.getFragmentInHours(aDate, Calendar.YEAR);
final Calendar cal = Calendar.getInstance(); final Calendar cal = Calendar.getInstance();
cal.setTime(aDate); cal.setTime(aDate);
assertEquals(hours + (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY assertEquals(hours + (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY / DateUtils.MILLIS_PER_HOUR, testResult);
/ DateUtils.MILLIS_PER_HOUR,
testResult);
} }
//Calendar.SECOND as useful fragment // Calendar.SECOND as useful fragment
@Test @Test
public void testInvalidFragmentWithCalendar() { public void testInvalidFragmentWithCalendar() {
@ -178,7 +170,7 @@ public class DateUtilsFragmentTest extends AbstractLangTest {
assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInDays(aDate, 0)); assertThrows(IllegalArgumentException.class, () -> DateUtils.getFragmentInDays(aDate, 0));
} }
//Calendar.MINUTE as useful fragment // Calendar.MINUTE as useful fragment
@Test @Test
public void testMillisecondFragmentInLargerUnitWithCalendar() { public void testMillisecondFragmentInLargerUnitWithCalendar() {
@ -207,7 +199,7 @@ public class DateUtilsFragmentTest extends AbstractLangTest {
assertEquals(expectedValue, testresult); assertEquals(expectedValue, testresult);
} }
//Calendar.DATE and Calendar.DAY_OF_YEAR as useful fragment // Calendar.DATE and Calendar.DAY_OF_YEAR as useful fragment
@Test @Test
public void testMillisecondsOfDayWithDate() { public void testMillisecondsOfDayWithDate() {
long testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DATE); long testresult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.DATE);
@ -217,7 +209,7 @@ public class DateUtilsFragmentTest extends AbstractLangTest {
assertEquals(expectedValue, testresult); assertEquals(expectedValue, testresult);
} }
//Calendar.HOUR_OF_DAY as useful fragment // Calendar.HOUR_OF_DAY as useful fragment
@Test @Test
public void testMillisecondsOfHourWithCalendar() { public void testMillisecondsOfHourWithCalendar() {
@ -246,18 +238,16 @@ public class DateUtilsFragmentTest extends AbstractLangTest {
@Test @Test
public void testMillisecondsOfMonthWithCalendar() { public void testMillisecondsOfMonthWithCalendar() {
final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MONTH); final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.MONTH);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR
+ hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY, + (days - 1) * DateUtils.MILLIS_PER_DAY, testResult);
testResult);
} }
//Calendar.MONTH as useful fragment // Calendar.MONTH as useful fragment
@Test @Test
public void testMillisecondsOfMonthWithDate() { public void testMillisecondsOfMonthWithDate() {
final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MONTH); final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.MONTH);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR
+ hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY, + (days - 1) * DateUtils.MILLIS_PER_DAY, testResult);
testResult);
} }
@Test @Test
@ -276,20 +266,18 @@ testResult);
@Test @Test
public void testMillisecondsOfYearWithCalendar() { public void testMillisecondsOfYearWithCalendar() {
final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.YEAR); final long testResult = DateUtils.getFragmentInMilliseconds(aCalendar, Calendar.YEAR);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR
+ hours * DateUtils.MILLIS_PER_HOUR + (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY, + (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY, testResult);
testResult);
} }
//Calendar.YEAR as useful fragment // Calendar.YEAR as useful fragment
@Test @Test
public void testMillisecondsOfYearWithDate() { public void testMillisecondsOfYearWithDate() {
final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.YEAR); final long testResult = DateUtils.getFragmentInMilliseconds(aDate, Calendar.YEAR);
final Calendar cal = Calendar.getInstance(); final Calendar cal = Calendar.getInstance();
cal.setTime(aDate); cal.setTime(aDate);
assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE assertEquals(millis + seconds * DateUtils.MILLIS_PER_SECOND + minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR
+ hours * DateUtils.MILLIS_PER_HOUR + (cal.get(Calendar.DAY_OF_YEAR) - 1)* DateUtils.MILLIS_PER_DAY, + (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY, testResult);
testResult);
} }
@Test @Test
@ -309,7 +297,7 @@ testResult);
@Test @Test
public void testMinutesOfDayWithCalendar() { public void testMinutesOfDayWithCalendar() {
long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DATE); long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DATE);
final long expectedValue = minutes + hours * DateUtils.MILLIS_PER_HOUR/ DateUtils.MILLIS_PER_MINUTE; final long expectedValue = minutes + hours * DateUtils.MILLIS_PER_HOUR / DateUtils.MILLIS_PER_MINUTE;
assertEquals(expectedValue, testResult); assertEquals(expectedValue, testResult);
testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DAY_OF_YEAR); testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testResult); assertEquals(expectedValue, testResult);
@ -318,7 +306,7 @@ testResult);
@Test @Test
public void testMinutesOfDayWithDate() { public void testMinutesOfDayWithDate() {
long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DATE); long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DATE);
final long expectedValue = minutes + hours * DateUtils.MILLIS_PER_HOUR/ DateUtils.MILLIS_PER_MINUTE; final long expectedValue = minutes + hours * DateUtils.MILLIS_PER_HOUR / DateUtils.MILLIS_PER_MINUTE;
assertEquals(expectedValue, testResult); assertEquals(expectedValue, testResult);
testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DAY_OF_YEAR); testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testResult); assertEquals(expectedValue, testResult);
@ -339,25 +327,20 @@ testResult);
@Test @Test
public void testMinutesOfMonthWithCalendar() { public void testMinutesOfMonthWithCalendar() {
final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.MONTH); final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.MONTH);
assertEquals( minutes +(hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY) assertEquals(minutes + (hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_MINUTE, testResult);
/ DateUtils.MILLIS_PER_MINUTE,
testResult);
} }
@Test @Test
public void testMinutesOfMonthWithDate() { public void testMinutesOfMonthWithDate() {
final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.MONTH); final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.MONTH);
assertEquals(minutes assertEquals(minutes + (hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_MINUTE, testResult);
+ (hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY)
/ DateUtils.MILLIS_PER_MINUTE,
testResult);
} }
@Test @Test
public void testMinutesOfYearWithCalendar() { public void testMinutesOfYearWithCalendar() {
final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.YEAR); final long testResult = DateUtils.getFragmentInMinutes(aCalendar, Calendar.YEAR);
assertEquals( minutes +(hours * DateUtils.MILLIS_PER_HOUR + (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY) assertEquals(minutes
/ DateUtils.MILLIS_PER_MINUTE, + (hours * DateUtils.MILLIS_PER_HOUR + (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_MINUTE,
testResult); testResult);
} }
@ -366,9 +349,8 @@ testResult);
final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.YEAR); final long testResult = DateUtils.getFragmentInMinutes(aDate, Calendar.YEAR);
final Calendar cal = Calendar.getInstance(); final Calendar cal = Calendar.getInstance();
cal.setTime(aDate); cal.setTime(aDate);
assertEquals(minutes assertEquals(
+ (hours * DateUtils.MILLIS_PER_HOUR + (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY) minutes + (hours * DateUtils.MILLIS_PER_HOUR + (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_MINUTE,
/ DateUtils.MILLIS_PER_MINUTE,
testResult); testResult);
} }
@ -382,7 +364,7 @@ testResult);
c.set(Calendar.SECOND, 0); c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0); c.set(Calendar.MILLISECOND, 0);
final long testResult = DateUtils.getFragmentInMinutes(c, Calendar.YEAR); final long testResult = DateUtils.getFragmentInMinutes(c, Calendar.YEAR);
assertEquals( 0, testResult); assertEquals(0, testResult);
} }
@Test @Test
@ -422,7 +404,7 @@ testResult);
@Test @Test
public void testSecondsOfDayWithCalendar() { public void testSecondsOfDayWithCalendar() {
long testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DATE); long testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DATE);
final long expectedValue = seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR)/ DateUtils.MILLIS_PER_SECOND; final long expectedValue = seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR) / DateUtils.MILLIS_PER_SECOND;
assertEquals(expectedValue, testresult); assertEquals(expectedValue, testresult);
testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DAY_OF_YEAR); testresult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testresult); assertEquals(expectedValue, testresult);
@ -431,7 +413,7 @@ testResult);
@Test @Test
public void testSecondsOfDayWithDate() { public void testSecondsOfDayWithDate() {
long testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DATE); long testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DATE);
final long expectedValue = seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR)/ DateUtils.MILLIS_PER_SECOND; final long expectedValue = seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR) / DateUtils.MILLIS_PER_SECOND;
assertEquals(expectedValue, testresult); assertEquals(expectedValue, testresult);
testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DAY_OF_YEAR); testresult = DateUtils.getFragmentInSeconds(aDate, Calendar.DAY_OF_YEAR);
assertEquals(expectedValue, testresult); assertEquals(expectedValue, testresult);
@ -440,21 +422,13 @@ testResult);
@Test @Test
public void testSecondsofHourWithCalendar() { public void testSecondsofHourWithCalendar() {
final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.HOUR_OF_DAY); final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.HOUR_OF_DAY);
assertEquals( assertEquals(seconds + minutes * DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND, testResult);
seconds
+ minutes
* DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND,
testResult);
} }
@Test @Test
public void testSecondsofHourWithDate() { public void testSecondsofHourWithDate() {
final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.HOUR_OF_DAY); final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.HOUR_OF_DAY);
assertEquals( assertEquals(seconds + minutes * DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND, testResult);
seconds
+ minutes
* DateUtils.MILLIS_PER_MINUTE / DateUtils.MILLIS_PER_SECOND,
testResult);
} }
@Test @Test
@ -473,34 +447,22 @@ testResult);
@Test @Test
public void testSecondsOfMonthWithCalendar() { public void testSecondsOfMonthWithCalendar() {
final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MONTH); final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.MONTH);
assertEquals( assertEquals(seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY)
seconds / DateUtils.MILLIS_PER_SECOND, testResult);
+ (minutes * DateUtils.MILLIS_PER_MINUTE
+ hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY)
/ DateUtils.MILLIS_PER_SECOND,
testResult);
} }
@Test @Test
public void testSecondsOfMonthWithDate() { public void testSecondsOfMonthWithDate() {
final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MONTH); final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.MONTH);
assertEquals( assertEquals(seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY)
seconds / DateUtils.MILLIS_PER_SECOND, testResult);
+ (minutes * DateUtils.MILLIS_PER_MINUTE
+ hours * DateUtils.MILLIS_PER_HOUR + (days - 1) * DateUtils.MILLIS_PER_DAY)
/ DateUtils.MILLIS_PER_SECOND,
testResult);
} }
@Test @Test
public void testSecondsOfYearWithCalendar() { public void testSecondsOfYearWithCalendar() {
final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.YEAR); final long testResult = DateUtils.getFragmentInSeconds(aCalendar, Calendar.YEAR);
assertEquals( assertEquals(seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR
seconds + (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY) / DateUtils.MILLIS_PER_SECOND, testResult);
+ (minutes * DateUtils.MILLIS_PER_MINUTE
+ hours * DateUtils.MILLIS_PER_HOUR + (aCalendar.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY)
/ DateUtils.MILLIS_PER_SECOND,
testResult);
} }
@Test @Test
@ -508,10 +470,8 @@ testResult);
final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.YEAR); final long testResult = DateUtils.getFragmentInSeconds(aDate, Calendar.YEAR);
final Calendar cal = Calendar.getInstance(); final Calendar cal = Calendar.getInstance();
cal.setTime(aDate); cal.setTime(aDate);
assertEquals( assertEquals(seconds
seconds + (minutes * DateUtils.MILLIS_PER_MINUTE + hours * DateUtils.MILLIS_PER_HOUR + (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY)
+ (minutes * DateUtils.MILLIS_PER_MINUTE
+ hours * DateUtils.MILLIS_PER_HOUR + (cal.get(Calendar.DAY_OF_YEAR) - 1) * DateUtils.MILLIS_PER_DAY)
/ DateUtils.MILLIS_PER_SECOND, / DateUtils.MILLIS_PER_SECOND,
testResult); testResult);
} }

View File

@ -70,13 +70,13 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
protected void baseRoundTest(final Date roundedUpDate, final Date roundedDownDate, final Date lastRoundDownDate, final int calendarField) { protected void baseRoundTest(final Date roundedUpDate, final Date roundedDownDate, final Date lastRoundDownDate, final int calendarField) {
final Date firstRoundUpDate = DateUtils.addMilliseconds(lastRoundDownDate, 1); final Date firstRoundUpDate = DateUtils.addMilliseconds(lastRoundDownDate, 1);
//Date-comparison // Date-comparison
assertEquals(roundedDownDate, DateUtils.round(roundedDownDate, calendarField)); assertEquals(roundedDownDate, DateUtils.round(roundedDownDate, calendarField));
assertEquals(roundedUpDate, DateUtils.round(roundedUpDate, calendarField)); assertEquals(roundedUpDate, DateUtils.round(roundedUpDate, calendarField));
assertEquals(roundedDownDate, DateUtils.round(lastRoundDownDate, calendarField)); assertEquals(roundedDownDate, DateUtils.round(lastRoundDownDate, calendarField));
assertEquals(roundedUpDate, DateUtils.round(firstRoundUpDate, calendarField)); assertEquals(roundedUpDate, DateUtils.round(firstRoundUpDate, calendarField));
//Calendar-initiations // Calendar-initiations
final Calendar roundedUpCalendar; final Calendar roundedUpCalendar;
final Calendar roundedDownCalendar; final Calendar roundedDownCalendar;
final Calendar lastRoundDownCalendar; final Calendar lastRoundDownCalendar;
@ -90,13 +90,13 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
lastRoundDownCalendar.setTime(lastRoundDownDate); lastRoundDownCalendar.setTime(lastRoundDownDate);
firstRoundUpCalendar.setTime(firstRoundUpDate); firstRoundUpCalendar.setTime(firstRoundUpDate);
//Calendar-comparison // Calendar-comparison
assertEquals(roundedDownCalendar, DateUtils.round(roundedDownCalendar, calendarField)); assertEquals(roundedDownCalendar, DateUtils.round(roundedDownCalendar, calendarField));
assertEquals(roundedUpCalendar, DateUtils.round(roundedUpCalendar, calendarField)); assertEquals(roundedUpCalendar, DateUtils.round(roundedUpCalendar, calendarField));
assertEquals(roundedDownCalendar, DateUtils.round(lastRoundDownCalendar, calendarField)); assertEquals(roundedDownCalendar, DateUtils.round(lastRoundDownCalendar, calendarField));
assertEquals(roundedUpCalendar, DateUtils.round(firstRoundUpCalendar, calendarField)); assertEquals(roundedUpCalendar, DateUtils.round(firstRoundUpCalendar, calendarField));
//Object-comparison // Object-comparison
assertEquals(roundedDownDate, DateUtils.round((Object) roundedDownDate, calendarField)); assertEquals(roundedDownDate, DateUtils.round((Object) roundedDownDate, calendarField));
assertEquals(roundedUpDate, DateUtils.round((Object) roundedUpDate, calendarField)); assertEquals(roundedUpDate, DateUtils.round((Object) roundedUpDate, calendarField));
assertEquals(roundedDownDate, DateUtils.round((Object) lastRoundDownDate, calendarField)); assertEquals(roundedDownDate, DateUtils.round((Object) lastRoundDownDate, calendarField));
@ -120,12 +120,14 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
protected void baseTruncateTest(final Date truncatedDate, final Date lastTruncateDate, final int calendarField) { protected void baseTruncateTest(final Date truncatedDate, final Date lastTruncateDate, final int calendarField) {
final Date nextTruncateDate = DateUtils.addMilliseconds(lastTruncateDate, 1); final Date nextTruncateDate = DateUtils.addMilliseconds(lastTruncateDate, 1);
//Date-comparison // Date-comparison
assertEquals(truncatedDate, DateUtils.truncate(truncatedDate, calendarField), "Truncating "+ fdf.format(truncatedDate) +" as Date with CalendarField-value "+ calendarField +" must return itself"); assertEquals(truncatedDate, DateUtils.truncate(truncatedDate, calendarField),
"Truncating " + fdf.format(truncatedDate) + " as Date with CalendarField-value " + calendarField + " must return itself");
assertEquals(truncatedDate, DateUtils.truncate(lastTruncateDate, calendarField)); assertEquals(truncatedDate, DateUtils.truncate(lastTruncateDate, calendarField));
assertNotEquals(truncatedDate, DateUtils.truncate(nextTruncateDate, calendarField), fdf.format(lastTruncateDate) + " is not an extreme when truncating as Date with CalendarField-value " + calendarField); assertNotEquals(truncatedDate, DateUtils.truncate(nextTruncateDate, calendarField),
fdf.format(lastTruncateDate) + " is not an extreme when truncating as Date with CalendarField-value " + calendarField);
//Calendar-initiations // Calendar-initiations
final Calendar truncatedCalendar; final Calendar truncatedCalendar;
final Calendar lastTruncateCalendar; final Calendar lastTruncateCalendar;
final Calendar nextTruncateCalendar; final Calendar nextTruncateCalendar;
@ -136,18 +138,24 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
lastTruncateCalendar.setTime(lastTruncateDate); lastTruncateCalendar.setTime(lastTruncateDate);
nextTruncateCalendar.setTime(nextTruncateDate); nextTruncateCalendar.setTime(nextTruncateDate);
//Calendar-comparison // Calendar-comparison
assertEquals(truncatedCalendar, DateUtils.truncate(truncatedCalendar, calendarField), "Truncating "+ fdf.format(truncatedCalendar) +" as Calendar with CalendarField-value "+ calendarField +" must return itself"); assertEquals(truncatedCalendar, DateUtils.truncate(truncatedCalendar, calendarField),
"Truncating " + fdf.format(truncatedCalendar) + " as Calendar with CalendarField-value " + calendarField + " must return itself");
assertEquals(truncatedCalendar, DateUtils.truncate(lastTruncateCalendar, calendarField)); assertEquals(truncatedCalendar, DateUtils.truncate(lastTruncateCalendar, calendarField));
assertNotEquals(truncatedCalendar, DateUtils.truncate(nextTruncateCalendar, calendarField), fdf.format(lastTruncateCalendar) + " is not an extreme when truncating as Calendar with CalendarField-value " + calendarField); assertNotEquals(truncatedCalendar, DateUtils.truncate(nextTruncateCalendar, calendarField),
fdf.format(lastTruncateCalendar) + " is not an extreme when truncating as Calendar with CalendarField-value " + calendarField);
//Object-comparison // Object-comparison
assertEquals(truncatedDate, DateUtils.truncate((Object) truncatedDate, calendarField), "Truncating "+ fdf.format(truncatedDate) +" as Date cast to Object with CalendarField-value "+ calendarField +" must return itself as Date"); assertEquals(truncatedDate, DateUtils.truncate((Object) truncatedDate, calendarField), "Truncating " + fdf.format(truncatedDate)
+ " as Date cast to Object with CalendarField-value " + calendarField + " must return itself as Date");
assertEquals(truncatedDate, DateUtils.truncate((Object) lastTruncateDate, calendarField)); assertEquals(truncatedDate, DateUtils.truncate((Object) lastTruncateDate, calendarField));
assertNotEquals(truncatedDate, DateUtils.truncate((Object) nextTruncateDate, calendarField), fdf.format(lastTruncateDate) + " is not an extreme when truncating as Date cast to Object with CalendarField-value " + calendarField); assertNotEquals(truncatedDate, DateUtils.truncate((Object) nextTruncateDate, calendarField),
assertEquals(truncatedDate, DateUtils.truncate((Object) truncatedCalendar, calendarField), "Truncating "+ fdf.format(truncatedCalendar) +" as Calendar cast to Object with CalendarField-value "+ calendarField +" must return itself as Date"); fdf.format(lastTruncateDate) + " is not an extreme when truncating as Date cast to Object with CalendarField-value " + calendarField);
assertEquals(truncatedDate, DateUtils.truncate((Object) truncatedCalendar, calendarField), "Truncating " + fdf.format(truncatedCalendar)
+ " as Calendar cast to Object with CalendarField-value " + calendarField + " must return itself as Date");
assertEquals(truncatedDate, DateUtils.truncate((Object) lastTruncateCalendar, calendarField)); assertEquals(truncatedDate, DateUtils.truncate((Object) lastTruncateCalendar, calendarField));
assertNotEquals(truncatedDate, DateUtils.truncate((Object) nextTruncateCalendar, calendarField), fdf.format(lastTruncateCalendar) + " is not an extreme when truncating as Calendar cast to Object with CalendarField-value " + calendarField); assertNotEquals(truncatedDate, DateUtils.truncate((Object) nextTruncateCalendar, calendarField),
fdf.format(lastTruncateCalendar) + " is not an extreme when truncating as Calendar cast to Object with CalendarField-value " + calendarField);
} }
/** /**
@ -160,7 +168,8 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
* @param calendarField a Calendar.field value * @param calendarField a Calendar.field value
*/ */
protected void roundToJanuaryFirst(final Date minDate, final Date maxDate, final int calendarField) { protected void roundToJanuaryFirst(final Date minDate, final Date maxDate, final int calendarField) {
assertEquals(januaryOneDate, DateUtils.round(januaryOneDate, calendarField), "Rounding "+ fdf.format(januaryOneDate) +" as Date with CalendarField-value "+ calendarField +" must return itself"); assertEquals(januaryOneDate, DateUtils.round(januaryOneDate, calendarField),
"Rounding " + fdf.format(januaryOneDate) + " as Date with CalendarField-value " + calendarField + " must return itself");
assertEquals(januaryOneDate, DateUtils.round(minDate, calendarField)); assertEquals(januaryOneDate, DateUtils.round(minDate, calendarField));
assertEquals(januaryOneDate, DateUtils.round(maxDate, calendarField)); assertEquals(januaryOneDate, DateUtils.round(maxDate, calendarField));
@ -168,21 +177,26 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
minCalendar.setTime(minDate); minCalendar.setTime(minDate);
final Calendar maxCalendar = Calendar.getInstance(); final Calendar maxCalendar = Calendar.getInstance();
maxCalendar.setTime(maxDate); maxCalendar.setTime(maxDate);
assertEquals(januaryOneCalendar, DateUtils.round(januaryOneCalendar, calendarField), "Rounding "+ fdf.format(januaryOneCalendar) +" as Date with CalendarField-value "+ calendarField +" must return itself"); assertEquals(januaryOneCalendar, DateUtils.round(januaryOneCalendar, calendarField),
"Rounding " + fdf.format(januaryOneCalendar) + " as Date with CalendarField-value " + calendarField + " must return itself");
assertEquals(januaryOneCalendar, DateUtils.round(minCalendar, calendarField)); assertEquals(januaryOneCalendar, DateUtils.round(minCalendar, calendarField));
assertEquals(januaryOneCalendar, DateUtils.round(maxCalendar, calendarField)); assertEquals(januaryOneCalendar, DateUtils.round(maxCalendar, calendarField));
final Date toPrevRoundDate = DateUtils.addMilliseconds(minDate, -1); final Date toPrevRoundDate = DateUtils.addMilliseconds(minDate, -1);
final Date toNextRoundDate = DateUtils.addMilliseconds(maxDate, 1); final Date toNextRoundDate = DateUtils.addMilliseconds(maxDate, 1);
assertNotEquals(januaryOneDate, DateUtils.round(toPrevRoundDate, calendarField), fdf.format(minDate) + " is not an lower-extreme when rounding as Date with CalendarField-value " + calendarField); assertNotEquals(januaryOneDate, DateUtils.round(toPrevRoundDate, calendarField),
assertNotEquals(januaryOneDate, DateUtils.round(toNextRoundDate, calendarField), fdf.format(maxDate) + " is not an upper-extreme when rounding as Date with CalendarField-value " + calendarField); fdf.format(minDate) + " is not an lower-extreme when rounding as Date with CalendarField-value " + calendarField);
assertNotEquals(januaryOneDate, DateUtils.round(toNextRoundDate, calendarField),
fdf.format(maxDate) + " is not an upper-extreme when rounding as Date with CalendarField-value " + calendarField);
final Calendar toPrevRoundCalendar = Calendar.getInstance(); final Calendar toPrevRoundCalendar = Calendar.getInstance();
toPrevRoundCalendar.setTime(toPrevRoundDate); toPrevRoundCalendar.setTime(toPrevRoundDate);
final Calendar toNextRoundCalendar = Calendar.getInstance(); final Calendar toNextRoundCalendar = Calendar.getInstance();
toNextRoundCalendar.setTime(toNextRoundDate); toNextRoundCalendar.setTime(toNextRoundDate);
assertNotEquals(januaryOneDate, DateUtils.round(toPrevRoundDate, calendarField), fdf.format(minCalendar) + " is not an lower-extreme when rounding as Date with CalendarField-value " + calendarField); assertNotEquals(januaryOneDate, DateUtils.round(toPrevRoundDate, calendarField),
assertNotEquals(januaryOneDate, DateUtils.round(toNextRoundDate, calendarField), fdf.format(maxCalendar) + " is not an upper-extreme when rounding as Date with CalendarField-value " + calendarField); fdf.format(minCalendar) + " is not an lower-extreme when rounding as Date with CalendarField-value " + calendarField);
assertNotEquals(januaryOneDate, DateUtils.round(toNextRoundDate, calendarField),
fdf.format(maxCalendar) + " is not an upper-extreme when rounding as Date with CalendarField-value " + calendarField);
} }
@BeforeEach @BeforeEach
@ -192,13 +206,13 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
targetYearDate = dateTimeParser.parse("January 1, 2007 0:00:00.000"); targetYearDate = dateTimeParser.parse("January 1, 2007 0:00:00.000");
targetDateDate = targetDayOfMonthDate = dateTimeParser.parse("June 1, 2008 0:00:00.000"); targetDateDate = targetDayOfMonthDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
targetAmDate = dateTimeParser.parse("June 1, 2008 0:00:00.000"); targetAmDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
targetPmDate = dateTimeParser.parse("June 1, 2008 12:00:00.000"); targetPmDate = dateTimeParser.parse("June 1, 2008 12:00:00.000");
targetHourDate = dateTimeParser.parse("June 1, 2008 8:00:00.000"); targetHourDate = dateTimeParser.parse("June 1, 2008 8:00:00.000");
targetHourOfDayDate = dateTimeParser.parse("June 1, 2008 8:00:00.000"); targetHourOfDayDate = dateTimeParser.parse("June 1, 2008 8:00:00.000");
targetMinuteDate = dateTimeParser.parse("June 1, 2008 8:15:00.000"); targetMinuteDate = dateTimeParser.parse("June 1, 2008 8:15:00.000");
targetSecondDate = dateTimeParser.parse("June 1, 2008 8:15:14.000"); targetSecondDate = dateTimeParser.parse("June 1, 2008 8:15:14.000");
targetMilliSecondDate = dateTimeParser.parse("June 1, 2008 8:15:14.231"); targetMilliSecondDate = dateTimeParser.parse("June 1, 2008 8:15:14.231");
januaryOneDate = dateTimeParser.parse("January 1, 2008 0:00:00.000"); januaryOneDate = dateTimeParser.parse("January 1, 2008 0:00:00.000");
januaryOneCalendar = Calendar.getInstance(); januaryOneCalendar = Calendar.getInstance();
@ -219,19 +233,19 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
final Date minDate; final Date minDate;
final Date maxDate; final Date maxDate;
//AM // AM
roundedUpDate = dateTimeParser.parse("June 1, 2008 12:00:00.000"); roundedUpDate = dateTimeParser.parse("June 1, 2008 12:00:00.000");
roundedDownDate = targetAmDate; roundedDownDate = targetAmDate;
lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 5:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 5:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//PM // PM
roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000");
roundedDownDate = targetPmDate; roundedDownDate = targetPmDate;
lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 17:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 17:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//round to January 1 // round to January 1
minDate = dateTimeParser.parse("December 31, 2007 18:00:00.000"); minDate = dateTimeParser.parse("December 31, 2007 18:00:00.000");
maxDate = dateTimeParser.parse("January 1, 2008 5:59:59.999"); maxDate = dateTimeParser.parse("January 1, 2008 5:59:59.999");
roundToJanuaryFirst(minDate, maxDate, calendarField); roundToJanuaryFirst(minDate, maxDate, calendarField);
@ -256,9 +270,9 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000");
roundedDownDate = targetDateDate; roundedDownDate = targetDateDate;
lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//round to January 1 // round to January 1
minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000"); minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000");
maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999"); maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999");
roundToJanuaryFirst(minDate, maxDate, calendarField); roundToJanuaryFirst(minDate, maxDate, calendarField);
@ -283,9 +297,9 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("June 2, 2008 0:00:00.000");
roundedDownDate = targetDayOfMonthDate; roundedDownDate = targetDayOfMonthDate;
lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 11:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//round to January 1 // round to January 1
minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000"); minDate = dateTimeParser.parse("December 31, 2007 12:00:00.000");
maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999"); maxDate = dateTimeParser.parse("January 1, 2008 11:59:59.999");
roundToJanuaryFirst(minDate, maxDate, calendarField); roundToJanuaryFirst(minDate, maxDate, calendarField);
@ -310,9 +324,9 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
roundedUpDate = dateTimeParser.parse("June 1, 2008 9:00:00.000"); roundedUpDate = dateTimeParser.parse("June 1, 2008 9:00:00.000");
roundedDownDate = targetHourDate; roundedDownDate = targetHourDate;
lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:29:59.999"); lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:29:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//round to January 1 // round to January 1
minDate = dateTimeParser.parse("December 31, 2007 23:30:00.000"); minDate = dateTimeParser.parse("December 31, 2007 23:30:00.000");
maxDate = dateTimeParser.parse("January 1, 2008 0:29:59.999"); maxDate = dateTimeParser.parse("January 1, 2008 0:29:59.999");
roundToJanuaryFirst(minDate, maxDate, calendarField); roundToJanuaryFirst(minDate, maxDate, calendarField);
@ -337,9 +351,9 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
roundedUpDate = dateTimeParser.parse("June 1, 2008 9:00:00.000"); roundedUpDate = dateTimeParser.parse("June 1, 2008 9:00:00.000");
roundedDownDate = targetHourOfDayDate; roundedDownDate = targetHourOfDayDate;
lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:29:59.999"); lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:29:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//round to January 1 // round to January 1
minDate = dateTimeParser.parse("December 31, 2007 23:30:00.000"); minDate = dateTimeParser.parse("December 31, 2007 23:30:00.000");
maxDate = dateTimeParser.parse("January 1, 2008 0:29:59.999"); maxDate = dateTimeParser.parse("January 1, 2008 0:29:59.999");
roundToJanuaryFirst(minDate, maxDate, calendarField); roundToJanuaryFirst(minDate, maxDate, calendarField);
@ -363,9 +377,9 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
roundedDownDate = lastRoundedDownDate = targetMilliSecondDate; roundedDownDate = lastRoundedDownDate = targetMilliSecondDate;
roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:14.232"); roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:14.232");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//round to January 1 // round to January 1
minDate = maxDate = januaryOneDate; minDate = maxDate = januaryOneDate;
roundToJanuaryFirst(minDate, maxDate, calendarField); roundToJanuaryFirst(minDate, maxDate, calendarField);
} }
@ -389,9 +403,9 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
roundedUpDate = dateTimeParser.parse("June 1, 2008 8:16:00.000"); roundedUpDate = dateTimeParser.parse("June 1, 2008 8:16:00.000");
roundedDownDate = targetMinuteDate; roundedDownDate = targetMinuteDate;
lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:29.999"); lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:29.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//round to January 1 // round to January 1
minDate = dateTimeParser.parse("December 31, 2007 23:59:30.000"); minDate = dateTimeParser.parse("December 31, 2007 23:59:30.000");
maxDate = dateTimeParser.parse("January 1, 2008 0:00:29.999"); maxDate = dateTimeParser.parse("January 1, 2008 0:00:29.999");
roundToJanuaryFirst(minDate, maxDate, calendarField); roundToJanuaryFirst(minDate, maxDate, calendarField);
@ -411,31 +425,31 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
final Date minDate; final Date minDate;
final Date maxDate; final Date maxDate;
//month with 28 days // month with 28 days
roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000"); roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000");
roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("February 14, 2007 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("February 14, 2007 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//month with 29 days // month with 29 days
roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("February 15, 2008 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("February 15, 2008 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//month with 30 days // month with 30 days
roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("April 15, 2008 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("April 15, 2008 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//month with 31 days // month with 31 days
roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("May 16, 2008 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("May 16, 2008 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//round to January 1 // round to January 1
minDate = dateTimeParser.parse("December 17, 2007 00:00:00.000"); minDate = dateTimeParser.parse("December 17, 2007 00:00:00.000");
maxDate = dateTimeParser.parse("January 16, 2008 23:59:59.999"); maxDate = dateTimeParser.parse("January 16, 2008 23:59:59.999");
roundToJanuaryFirst(minDate, maxDate, calendarField); roundToJanuaryFirst(minDate, maxDate, calendarField);
@ -460,9 +474,9 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:15.000"); roundedUpDate = dateTimeParser.parse("June 1, 2008 8:15:15.000");
roundedDownDate = targetSecondDate; roundedDownDate = targetSecondDate;
lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:14.499"); lastRoundedDownDate = dateTimeParser.parse("June 1, 2008 8:15:14.499");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//round to January 1 // round to January 1
minDate = dateTimeParser.parse("December 31, 2007 23:59:59.500"); minDate = dateTimeParser.parse("December 31, 2007 23:59:59.500");
maxDate = dateTimeParser.parse("January 1, 2008 0:00:00.499"); maxDate = dateTimeParser.parse("January 1, 2008 0:00:00.499");
roundToJanuaryFirst(minDate, maxDate, calendarField); roundToJanuaryFirst(minDate, maxDate, calendarField);
@ -482,55 +496,55 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
final Date minDate; final Date minDate;
final Date maxDate; final Date maxDate;
//month with 28 days (1) // month with 28 days (1)
roundedUpDate = dateTimeParser.parse("February 16, 2007 0:00:00.000"); roundedUpDate = dateTimeParser.parse("February 16, 2007 0:00:00.000");
roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 1, 2007 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("February 8, 2007 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("February 8, 2007 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//month with 28 days (2) // month with 28 days (2)
roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000"); roundedUpDate = dateTimeParser.parse("March 1, 2007 0:00:00.000");
roundedDownDate = dateTimeParser.parse("February 16, 2007 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 16, 2007 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("February 23, 2007 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("February 23, 2007 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//month with 29 days (1) // month with 29 days (1)
roundedUpDate = dateTimeParser.parse("February 16, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("February 16, 2008 0:00:00.000");
roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 1, 2008 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("February 8, 2008 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("February 8, 2008 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//month with 29 days (2) // month with 29 days (2)
roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
roundedDownDate = dateTimeParser.parse("February 16, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("February 16, 2008 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("February 23, 2008 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("February 23, 2008 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//month with 30 days (1) // month with 30 days (1)
roundedUpDate = dateTimeParser.parse("April 16, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("April 16, 2008 0:00:00.000");
roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("April 1, 2008 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("April 8, 2008 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("April 8, 2008 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//month with 30 days (2) // month with 30 days (2)
roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
roundedDownDate = dateTimeParser.parse("April 16, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("April 16, 2008 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("April 23, 2008 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("April 23, 2008 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//month with 31 days (1) // month with 31 days (1)
roundedUpDate = dateTimeParser.parse("May 16, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("May 16, 2008 0:00:00.000");
roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("May 1, 2008 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("May 8, 2008 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("May 8, 2008 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//month with 31 days (2) // month with 31 days (2)
roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000"); roundedUpDate = dateTimeParser.parse("June 1, 2008 0:00:00.000");
roundedDownDate = dateTimeParser.parse("May 16, 2008 0:00:00.000"); roundedDownDate = dateTimeParser.parse("May 16, 2008 0:00:00.000");
lastRoundedDownDate = dateTimeParser.parse("May 23, 2008 23:59:59.999"); lastRoundedDownDate = dateTimeParser.parse("May 23, 2008 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
//round to January 1 // round to January 1
minDate = dateTimeParser.parse("December 24, 2007 00:00:00.000"); minDate = dateTimeParser.parse("December 24, 2007 00:00:00.000");
maxDate = dateTimeParser.parse("January 8, 2008 23:59:59.999"); maxDate = dateTimeParser.parse("January 8, 2008 23:59:59.999");
roundToJanuaryFirst(minDate, maxDate, calendarField); roundToJanuaryFirst(minDate, maxDate, calendarField);
@ -547,7 +561,7 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
final Date roundedUpDate = dateTimeParser.parse("January 1, 2008 0:00:00.000"); final Date roundedUpDate = dateTimeParser.parse("January 1, 2008 0:00:00.000");
final Date roundedDownDate = targetYearDate; final Date roundedDownDate = targetYearDate;
final Date lastRoundedDownDate = dateTimeParser.parse("June 30, 2007 23:59:59.999"); final Date lastRoundedDownDate = dateTimeParser.parse("June 30, 2007 23:59:59.999");
baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField); baseRoundTest(roundedUpDate, roundedDownDate, lastRoundedDownDate, calendarField);
} }
/** /**
@ -559,12 +573,10 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
@Test @Test
public void testTruncateAmPm() throws Exception { public void testTruncateAmPm() throws Exception {
final int calendarField = Calendar.AM_PM; final int calendarField = Calendar.AM_PM;
// AM
//AM
Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 11:59:59.999"); Date lastTruncateDate = dateTimeParser.parse("June 1, 2008 11:59:59.999");
baseTruncateTest(targetAmDate, lastTruncateDate, calendarField); baseTruncateTest(targetAmDate, lastTruncateDate, calendarField);
// PM
//PM
lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999"); lastTruncateDate = dateTimeParser.parse("June 1, 2008 23:59:59.999");
baseTruncateTest(targetPmDate, lastTruncateDate, calendarField); baseTruncateTest(targetPmDate, lastTruncateDate, calendarField);
} }
@ -674,42 +686,42 @@ public class DateUtilsRoundingTest extends AbstractLangTest {
final int calendarField = DateUtils.SEMI_MONTH; final int calendarField = DateUtils.SEMI_MONTH;
Date truncatedDate, lastTruncateDate; Date truncatedDate, lastTruncateDate;
//month with 28 days (1) // month with 28 days (1)
truncatedDate = dateTimeParser.parse("February 1, 2007 0:00:00.000"); truncatedDate = dateTimeParser.parse("February 1, 2007 0:00:00.000");
lastTruncateDate = dateTimeParser.parse("February 15, 2007 23:59:59.999"); lastTruncateDate = dateTimeParser.parse("February 15, 2007 23:59:59.999");
baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
//month with 28 days (2) // month with 28 days (2)
truncatedDate = dateTimeParser.parse("February 16, 2007 0:00:00.000"); truncatedDate = dateTimeParser.parse("February 16, 2007 0:00:00.000");
lastTruncateDate = dateTimeParser.parse("February 28, 2007 23:59:59.999"); lastTruncateDate = dateTimeParser.parse("February 28, 2007 23:59:59.999");
baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
//month with 29 days (1) // month with 29 days (1)
truncatedDate = dateTimeParser.parse("February 1, 2008 0:00:00.000"); truncatedDate = dateTimeParser.parse("February 1, 2008 0:00:00.000");
lastTruncateDate = dateTimeParser.parse("February 15, 2008 23:59:59.999"); lastTruncateDate = dateTimeParser.parse("February 15, 2008 23:59:59.999");
baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
//month with 29 days (2) // month with 29 days (2)
truncatedDate = dateTimeParser.parse("February 16, 2008 0:00:00.000"); truncatedDate = dateTimeParser.parse("February 16, 2008 0:00:00.000");
lastTruncateDate = dateTimeParser.parse("February 29, 2008 23:59:59.999"); lastTruncateDate = dateTimeParser.parse("February 29, 2008 23:59:59.999");
baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
//month with 30 days (1) // month with 30 days (1)
truncatedDate = dateTimeParser.parse("April 1, 2008 0:00:00.000"); truncatedDate = dateTimeParser.parse("April 1, 2008 0:00:00.000");
lastTruncateDate = dateTimeParser.parse("April 15, 2008 23:59:59.999"); lastTruncateDate = dateTimeParser.parse("April 15, 2008 23:59:59.999");
baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
//month with 30 days (2) // month with 30 days (2)
truncatedDate = dateTimeParser.parse("April 16, 2008 0:00:00.000"); truncatedDate = dateTimeParser.parse("April 16, 2008 0:00:00.000");
lastTruncateDate = dateTimeParser.parse("April 30, 2008 23:59:59.999"); lastTruncateDate = dateTimeParser.parse("April 30, 2008 23:59:59.999");
baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
//month with 31 days (1) // month with 31 days (1)
truncatedDate = dateTimeParser.parse("March 1, 2008 0:00:00.000"); truncatedDate = dateTimeParser.parse("March 1, 2008 0:00:00.000");
lastTruncateDate = dateTimeParser.parse("March 15, 2008 23:59:59.999"); lastTruncateDate = dateTimeParser.parse("March 15, 2008 23:59:59.999");
baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);
//month with 31 days (2) // month with 31 days (2)
truncatedDate = dateTimeParser.parse("March 16, 2008 0:00:00.000"); truncatedDate = dateTimeParser.parse("March 16, 2008 0:00:00.000");
lastTruncateDate = dateTimeParser.parse("March 31, 2008 23:59:59.999"); lastTruncateDate = dateTimeParser.parse("March 31, 2008 23:59:59.999");
baseTruncateTest(truncatedDate, lastTruncateDate, calendarField); baseTruncateTest(truncatedDate, lastTruncateDate, calendarField);

View File

@ -1661,13 +1661,13 @@ public class DateUtilsTest extends AbstractLangTest {
@Test @Test
public void testWeekIterator() { public void testWeekIterator() {
final Calendar now = Calendar.getInstance(); final Calendar now = Calendar.getInstance();
for (int i = 0; i< 7; i++) { for (int i = 0; i < 7; i++) {
final Calendar today = DateUtils.truncate(now, Calendar.DATE); final Calendar today = DateUtils.truncate(now, Calendar.DATE);
final Calendar sunday = DateUtils.truncate(now, Calendar.DATE); final Calendar sunday = DateUtils.truncate(now, Calendar.DATE);
sunday.add(Calendar.DATE, 1 - sunday.get(Calendar.DAY_OF_WEEK)); sunday.add(Calendar.DATE, 1 - sunday.get(Calendar.DAY_OF_WEEK));
final Calendar monday = DateUtils.truncate(now, Calendar.DATE); final Calendar monday = DateUtils.truncate(now, Calendar.DATE);
if (monday.get(Calendar.DAY_OF_WEEK) == 1) { if (monday.get(Calendar.DAY_OF_WEEK) == 1) {
//This is sunday... roll back 6 days // This is sunday... roll back 6 days
monday.add(Calendar.DATE, -6); monday.add(Calendar.DATE, -6);
} else { } else {
monday.add(Calendar.DATE, 2 - monday.get(Calendar.DAY_OF_WEEK)); monday.add(Calendar.DATE, 2 - monday.get(Calendar.DAY_OF_WEEK));

View File

@ -72,12 +72,12 @@ public class DurationFormatUtilsTest extends AbstractLangTest {
c.set(year, month, day, 0, 0, 0); c.set(year, month, day, 0, 0, 0);
final int[] array1 = { year, month, day, 0, 0, 0 }; final int[] array1 = { year, month, day, 0, 0, 0 };
final int[] array2 = { year, month, day, 0, 0, 0 }; final int[] array2 = { year, month, day, 0, 0, 0 };
for (int i=0; i < FOUR_YEARS; i++) { for (int i = 0; i < FOUR_YEARS; i++) {
array2[0] = c.get(Calendar.YEAR); array2[0] = c.get(Calendar.YEAR);
array2[1] = c.get(Calendar.MONTH); array2[1] = c.get(Calendar.MONTH);
array2[2] = c.get(Calendar.DAY_OF_MONTH); array2[2] = c.get(Calendar.DAY_OF_MONTH);
final String tmpMsg = msg + array2[0] + "-" + array2[1] + "-" + array2[2] + " at "; final String tmpMsg = msg + array2[0] + "-" + array2[1] + "-" + array2[2] + " at ";
assertEqualDuration(tmpMsg + i, Integer.toString(i), array1, array2, format ); assertEqualDuration(tmpMsg + i, Integer.toString(i), array1, array2, format);
c.add(calendarType, 1); c.add(calendarType, 1);
} }
} }
@ -93,37 +93,17 @@ public class DurationFormatUtilsTest extends AbstractLangTest {
@Test @Test
public void testAlternatingLiteralOptionals() { public void testAlternatingLiteralOptionals() {
final String format = "['d'dH'h'][m'm']['s's]['ms'S]"; final String format = "['d'dH'h'][m'm']['s's]['ms'S]";
assertEquals("d1", DurationFormatUtils.formatDuration(Duration.ofDays(1).toMillis(), format));
assertEquals("d1", assertEquals("1h", DurationFormatUtils.formatDuration(Duration.ofHours(1).toMillis(), format));
DurationFormatUtils.formatDuration(Duration.ofDays(1).toMillis(), format)); assertEquals("1m", DurationFormatUtils.formatDuration(Duration.ofMinutes(1).toMillis(), format));
assertEquals("s1", DurationFormatUtils.formatDuration(Duration.ofSeconds(1).toMillis(), format));
assertEquals("1h", assertEquals("ms001", DurationFormatUtils.formatDuration(Duration.ofMillis(1).toMillis(), format));
DurationFormatUtils.formatDuration(Duration.ofHours(1).toMillis(), format)); assertEquals("d1s1", DurationFormatUtils.formatDuration(Duration.ofDays(1).plusSeconds(1).toMillis(), format));
assertEquals("d11h", DurationFormatUtils.formatDuration(Duration.ofDays(1).plusHours(1).toMillis(), format));
assertEquals("1m", assertEquals("d11h1m", DurationFormatUtils.formatDuration(Duration.ofDays(1).plusHours(1).plusMinutes(1).toMillis(), format));
DurationFormatUtils.formatDuration(Duration.ofMinutes(1).toMillis(), format)); assertEquals("d11h1ms1", DurationFormatUtils.formatDuration(Duration.ofDays(1).plusHours(1).plusMinutes(1).plusSeconds(1).toMillis(), format));
assertEquals("s1",
DurationFormatUtils.formatDuration(Duration.ofSeconds(1).toMillis(), format));
assertEquals("ms001",
DurationFormatUtils.formatDuration(Duration.ofMillis(1).toMillis(), format));
assertEquals("d1s1",
DurationFormatUtils.formatDuration(Duration.ofDays(1).plusSeconds(1).toMillis(), format));
assertEquals("d11h",
DurationFormatUtils.formatDuration(Duration.ofDays(1).plusHours(1).toMillis(), format));
assertEquals("d11h1m",
DurationFormatUtils.formatDuration(Duration.ofDays(1).plusHours(1).plusMinutes(1).toMillis(), format));
assertEquals("d11h1ms1",
DurationFormatUtils.formatDuration(Duration.ofDays(1).plusHours(1).plusMinutes(1).plusSeconds(1).toMillis(), format));
assertEquals("d11h1ms1ms001", assertEquals("d11h1ms1ms001",
DurationFormatUtils.formatDuration(Duration.ofDays(1).plusHours(1).plusMinutes(1).plusSeconds(1).plusMillis(1).toMillis(), format)); DurationFormatUtils.formatDuration(Duration.ofDays(1).plusHours(1).plusMinutes(1).plusSeconds(1).plusMillis(1).toMillis(), format));
} }
/** See https://issues.apache.org/bugzilla/show_bug.cgi?id=38401 */ /** See https://issues.apache.org/bugzilla/show_bug.cgi?id=38401 */
@ -613,7 +593,7 @@ public class DurationFormatUtilsTest extends AbstractLangTest {
public void testLANG984() { // Long durations public void testLANG984() { // Long durations
assertEquals("0", DurationFormatUtils.formatDuration(0, "S")); assertEquals("0", DurationFormatUtils.formatDuration(0, "S"));
assertEquals(Integer.toString(Integer.MAX_VALUE), DurationFormatUtils.formatDuration(Integer.MAX_VALUE, "S")); assertEquals(Integer.toString(Integer.MAX_VALUE), DurationFormatUtils.formatDuration(Integer.MAX_VALUE, "S"));
long maxIntPlus=Integer.MAX_VALUE; long maxIntPlus = Integer.MAX_VALUE;
maxIntPlus++; maxIntPlus++;
assertEquals(Long.toString(maxIntPlus), DurationFormatUtils.formatDuration(maxIntPlus, "S")); assertEquals(Long.toString(maxIntPlus), DurationFormatUtils.formatDuration(maxIntPlus, "S"));
assertEquals(Long.toString(Long.MAX_VALUE), DurationFormatUtils.formatDuration(Long.MAX_VALUE, "S")); assertEquals(Long.toString(Long.MAX_VALUE), DurationFormatUtils.formatDuration(Long.MAX_VALUE, "S"));
@ -622,27 +602,27 @@ public class DurationFormatUtilsTest extends AbstractLangTest {
@Test @Test
public void testLexx() { public void testLexx() {
// tests each constant // tests each constant
assertArrayEquals(new DurationFormatUtils.Token[]{ assertArrayEquals(new DurationFormatUtils.Token[] {
createTokenWithCount(DurationFormatUtils.y, 1), createTokenWithCount(DurationFormatUtils.y, 1),
createTokenWithCount(DurationFormatUtils.M, 1), createTokenWithCount(DurationFormatUtils.M, 1),
createTokenWithCount(DurationFormatUtils.d, 1), createTokenWithCount(DurationFormatUtils.d, 1),
createTokenWithCount(DurationFormatUtils.H, 1), createTokenWithCount(DurationFormatUtils.H, 1),
createTokenWithCount(DurationFormatUtils.m, 1), createTokenWithCount(DurationFormatUtils.m, 1),
createTokenWithCount(DurationFormatUtils.s, 1), createTokenWithCount(DurationFormatUtils.s, 1),
createTokenWithCount(DurationFormatUtils.S, 1)}, DurationFormatUtils.lexx("yMdHmsS")); createTokenWithCount(DurationFormatUtils.S, 1) }, DurationFormatUtils.lexx("yMdHmsS"));
// tests the ISO 8601-like // tests the ISO 8601-like
assertArrayEquals(new DurationFormatUtils.Token[]{ assertArrayEquals(new DurationFormatUtils.Token[] {
createTokenWithCount(DurationFormatUtils.H, 2), createTokenWithCount(DurationFormatUtils.H, 2),
createTokenWithCount(new StringBuilder(":"), 1), createTokenWithCount(new StringBuilder(":"), 1),
createTokenWithCount(DurationFormatUtils.m, 2), createTokenWithCount(DurationFormatUtils.m, 2),
createTokenWithCount(new StringBuilder(":"), 1), createTokenWithCount(new StringBuilder(":"), 1),
createTokenWithCount(DurationFormatUtils.s, 2), createTokenWithCount(DurationFormatUtils.s, 2),
createTokenWithCount(new StringBuilder("."), 1), createTokenWithCount(new StringBuilder("."), 1),
createTokenWithCount(DurationFormatUtils.S, 3)}, DurationFormatUtils.lexx("HH:mm:ss.SSS")); createTokenWithCount(DurationFormatUtils.S, 3) }, DurationFormatUtils.lexx("HH:mm:ss.SSS"));
// test the iso extended format // test the iso extended format
assertArrayEquals(new DurationFormatUtils.Token[]{ assertArrayEquals(new DurationFormatUtils.Token[] {
createTokenWithCount(new StringBuilder("P"), 1), createTokenWithCount(new StringBuilder("P"), 1),
createTokenWithCount(DurationFormatUtils.y, 4), createTokenWithCount(DurationFormatUtils.y, 4),
createTokenWithCount(new StringBuilder("Y"), 1), createTokenWithCount(new StringBuilder("Y"), 1),
@ -657,8 +637,7 @@ public class DurationFormatUtilsTest extends AbstractLangTest {
createTokenWithCount(DurationFormatUtils.s, 1), createTokenWithCount(DurationFormatUtils.s, 1),
createTokenWithCount(new StringBuilder("."), 1), createTokenWithCount(new StringBuilder("."), 1),
createTokenWithCount(DurationFormatUtils.S, 3), createTokenWithCount(DurationFormatUtils.S, 3),
createTokenWithCount(new StringBuilder("S"), 1)}, DurationFormatUtils createTokenWithCount(new StringBuilder("S"), 1) }, DurationFormatUtils.lexx(DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN));
.lexx(DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN));
// test failures in equals // test failures in equals
final DurationFormatUtils.Token token = createTokenWithCount(DurationFormatUtils.y, 4); final DurationFormatUtils.Token token = createTokenWithCount(DurationFormatUtils.y, 4);
@ -671,25 +650,17 @@ public class DurationFormatUtilsTest extends AbstractLangTest {
@Test @Test
public void testLiteralPrefixOptionalToken() { public void testLiteralPrefixOptionalToken() {
assertEquals( assertEquals(DurationFormatUtils.formatDuration(10000L, "s's'"), DurationFormatUtils.formatDuration(10000L, "['['d']']['<'H'>']['{'m'}']s's'"));
DurationFormatUtils.formatDuration(10000L, "s's'"), assertEquals(DurationFormatUtils.formatDuration(10000L, "s's'"), DurationFormatUtils.formatDuration(10000L, "['{'m'}']s's'"));
DurationFormatUtils.formatDuration(10000L, "['['d']']['<'H'>']['{'m'}']s's'"));
assertEquals(
DurationFormatUtils.formatDuration(10000L, "s's'"),
DurationFormatUtils.formatDuration(10000L, "['{'m'}']s's'"));
} }
// Testing the under a day range in DurationFormatUtils.formatPeriod // Testing the under a day range in DurationFormatUtils.formatPeriod
@Test @Test
public void testLowDurations() { public void testLowDurations() {
for (int hr=0; hr < 24; hr++) { for (int hr = 0; hr < 24; hr++) {
for (int min=0; min < 60; min++) { for (int min = 0; min < 60; min++) {
for (int sec=0; sec < 60; sec++) { for (int sec = 0; sec < 60; sec++) {
assertEqualDuration(hr + ":" + min + ":" + sec, assertEqualDuration(hr + ":" + min + ":" + sec, new int[] { 2000, 0, 1, 0, 0, 0, 0 }, new int[] { 2000, 0, 1, hr, min, sec }, "H:m:s");
new int[] { 2000, 0, 1, 0, 0, 0, 0 },
new int[] { 2000, 0, 1, hr, min, sec },
"H:m:s"
);
} }
} }
} }
@ -697,14 +668,10 @@ public class DurationFormatUtilsTest extends AbstractLangTest {
@Test @Test
public void testMultipleOptionalBlocks() { public void testMultipleOptionalBlocks() {
assertEquals(DurationFormatUtils.formatDuration(Duration.ofHours(1).toMillis(), "'[['H']]'"),
assertEquals( DurationFormatUtils.formatDuration(Duration.ofHours(1).toMillis(), "['{'d'}']['[['H']]']"));
DurationFormatUtils.formatDuration(Duration.ofHours(1).toMillis(), "'[['H']]'"), assertEquals(DurationFormatUtils.formatDuration(Duration.ofDays(1).toMillis(), "['{'d'}']"),
DurationFormatUtils.formatDuration(Duration.ofHours(1).toMillis(), "['{'d'}']['[['H']]']")); DurationFormatUtils.formatDuration(Duration.ofDays(1).toMillis(), "['{'d'}']['['H']']"));
assertEquals(
DurationFormatUtils.formatDuration(Duration.ofDays(1).toMillis(), "['{'d'}']"),
DurationFormatUtils.formatDuration(Duration.ofDays(1).toMillis(), "['{'d'}']['['H']']"));
} }
@Test @Test

View File

@ -273,13 +273,11 @@ public class FastDateFormatTest extends AbstractLangTest {
public void testParseSync() throws InterruptedException { public void testParseSync() throws InterruptedException {
final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS"; final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
final SimpleDateFormat inner = new SimpleDateFormat(pattern); final SimpleDateFormat inner = new SimpleDateFormat(pattern);
final Format sdf= new Format() { final Format sdf = new Format() {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
@Override @Override
public StringBuffer format(final Object obj, public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition fieldPosition) {
final StringBuffer toAppendTo,
final FieldPosition fieldPosition) {
synchronized (this) { synchronized (this) {
return inner.format(obj, toAppendTo, fieldPosition); return inner.format(obj, toAppendTo, fieldPosition);
} }
@ -292,13 +290,13 @@ public class FastDateFormatTest extends AbstractLangTest {
} }
} }
}; };
final AtomicLongArray sdfTime= measureTime(sdf, sdf); final AtomicLongArray sdfTime = measureTime(sdf, sdf);
final Format fdf = FastDateFormat.getInstance(pattern); final Format fdf = FastDateFormat.getInstance(pattern);
final AtomicLongArray fdfTime= measureTime(fdf, fdf); final AtomicLongArray fdfTime = measureTime(fdf, fdf);
//System.out.println(">>FastDateFormatTest: FastDatePrinter:"+fdfTime.get(0)+" SimpleDateFormat:"+sdfTime.get(0)); // System.out.println(">>FastDateFormatTest: FastDatePrinter:"+fdfTime.get(0)+" SimpleDateFormat:"+sdfTime.get(0));
//System.out.println(">>FastDateFormatTest: FastDateParser:"+fdfTime.get(1)+" SimpleDateFormat:"+sdfTime.get(1)); // System.out.println(">>FastDateFormatTest: FastDateParser:"+fdfTime.get(1)+" SimpleDateFormat:"+sdfTime.get(1));
} }
@Test @Test

View File

@ -42,6 +42,7 @@ public class FastDateParserSDFTest extends AbstractLangTest {
private static final TimeZone timeZone = TimeZone.getDefault(); private static final TimeZone timeZone = TimeZone.getDefault();
public static Stream<Arguments> data() { public static Stream<Arguments> data() {
// @formatter:off
return Stream.of( return Stream.of(
// General Time zone tests // General Time zone tests
Arguments.of("z yyyy", "GMT 2010", Locale.UK, true), // no offset specified, but this is allowed as a TimeZone name Arguments.of("z yyyy", "GMT 2010", Locale.UK, true), // no offset specified, but this is allowed as a TimeZone name
@ -103,13 +104,14 @@ public class FastDateParserSDFTest extends AbstractLangTest {
Arguments.of( "hh", "48", Locale.UK, true), // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0 Arguments.of( "hh", "48", Locale.UK, true), // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0
Arguments.of( "kk", "48", Locale.UK, true) // Hour in day (1-24), i.e. midnight is 24, not 0 Arguments.of( "kk", "48", Locale.UK, true) // Hour in day (1-24), i.e. midnight is 24, not 0
); );
// @formatter:on
} }
private void checkParse(final String formattedDate, final String format, final Locale locale, final boolean valid) { private void checkParse(final String formattedDate, final String format, final Locale locale, final boolean valid) {
final SimpleDateFormat sdf = new SimpleDateFormat(format, locale); final SimpleDateFormat sdf = new SimpleDateFormat(format, locale);
sdf.setTimeZone(timeZone); sdf.setTimeZone(timeZone);
final DateParser fdf = new FastDateParser(format, timeZone, locale); final DateParser fdf = new FastDateParser(format, timeZone, locale);
Date expectedTime=null; Date expectedTime = null;
Class<?> sdfE = null; Class<?> sdfE = null;
try { try {
expectedTime = sdf.parse(formattedDate); expectedTime = sdf.parse(formattedDate);
@ -173,11 +175,10 @@ public class FastDateParserSDFTest extends AbstractLangTest {
final int endIndex = fdfP.getIndex(); final int endIndex = fdfP.getIndex();
final int length = formattedDate.length(); final int length = formattedDate.length();
assertEquals(length, endIndex, "Expected FDF to parse full string " + fdfP); assertEquals(length, endIndex, "Expected FDF to parse full string " + fdfP);
assertEquals(expectedTime, actualTime, locale +" "+formattedDate +"\n"); assertEquals(expectedTime, actualTime, locale + " " + formattedDate + "\n");
} else { } else {
assertNotEquals(-1, fdferrorIndex, "Test data error: expected FDF parse to fail, but got " + actualTime); assertNotEquals(-1, fdferrorIndex, "Test data error: expected FDF parse to fail, but got " + actualTime);
assertTrue(sdferrorIndex - fdferrorIndex <= 4, assertTrue(sdferrorIndex - fdferrorIndex <= 4, "FDF error index (" + fdferrorIndex + ") should approximate SDF index (" + sdferrorIndex + ")");
"FDF error index ("+ fdferrorIndex + ") should approximate SDF index (" + sdferrorIndex + ")");
} }
} }

View File

@ -42,14 +42,14 @@ import org.junitpioneer.jupiter.DefaultTimeZone;
public class FastDatePrinterTest extends AbstractLangTest { public class FastDatePrinterTest extends AbstractLangTest {
private enum Expected1806 { private enum Expected1806 {
India(INDIA, "+05", "+0530", "+05:30"), Greenwich(TimeZones.GMT, "Z", "Z", "Z"), NewYork( India(INDIA, "+05", "+0530", "+05:30"), Greenwich(TimeZones.GMT, "Z", "Z", "Z"), NewYork(NEW_YORK, "-05", "-0500", "-05:00");
NEW_YORK, "-05", "-0500", "-05:00");
final TimeZone zone; final TimeZone zone;
final String one; final String one;
final String two; final String two;
final String three; final String three;
Expected1806(final TimeZone zone, final String one, final String two, final String three) { Expected1806(final TimeZone zone, final String one, final String two, final String three) {
this.zone = zone; this.zone = zone;
this.one = one; this.one = one;
@ -57,6 +57,7 @@ public class FastDatePrinterTest extends AbstractLangTest {
this.three = three; this.three = three;
} }
} }
private static final String YYYY_MM_DD = "yyyy/MM/dd"; private static final String YYYY_MM_DD = "yyyy/MM/dd";
private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York"); private static final TimeZone NEW_YORK = TimeZone.getTimeZone("America/New_York");
private static final TimeZone INDIA = TimeZone.getTimeZone("Asia/Calcutta"); private static final TimeZone INDIA = TimeZone.getTimeZone("Asia/Calcutta");
@ -93,9 +94,10 @@ public class FastDatePrinterTest extends AbstractLangTest {
/** /**
* Override this method in derived tests to change the construction of instances * Override this method in derived tests to change the construction of instances
* @param format the format string to use *
* @param format the format string to use
* @param timeZone the time zone to use * @param timeZone the time zone to use
* @param locale the locale to use * @param locale the locale to use
* @return the DatePrinter to use for testing * @return the DatePrinter to use for testing
*/ */
protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale) { protected DatePrinter getInstance(final String format, final TimeZone timeZone, final Locale locale) {
@ -117,6 +119,7 @@ public class FastDatePrinterTest extends AbstractLangTest {
assertEquals(trial.three, printer.format(cal)); assertEquals(trial.three, printer.format(cal));
} }
} }
@Test @Test
public void test1806Argument() { public void test1806Argument() {
assertThrows(IllegalArgumentException.class, () -> getInstance("XXXX")); assertThrows(IllegalArgumentException.class, () -> getInstance("XXXX"));
@ -155,8 +158,8 @@ public class FastDatePrinterTest extends AbstractLangTest {
@Test @Test
public void testEquals() { public void testEquals() {
final DatePrinter printer1= getInstance(YYYY_MM_DD); final DatePrinter printer1 = getInstance(YYYY_MM_DD);
final DatePrinter printer2= getInstance(YYYY_MM_DD); final DatePrinter printer2 = getInstance(YYYY_MM_DD);
assertEquals(printer1, printer2); assertEquals(printer1, printer2);
assertEquals(printer1.hashCode(), printer2.hashCode()); assertEquals(printer1.hashCode(), printer2.hashCode());
@ -203,8 +206,8 @@ public class FastDatePrinterTest extends AbstractLangTest {
assertEquals("-04:00", fdf.format(cal2)); assertEquals("-04:00", fdf.format(cal2));
assertEquals("-04:00", fdf.format(millis2)); assertEquals("-04:00", fdf.format(millis2));
final String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M LLLL LLL LL L" + final String pattern = "GGGG GGG GG G yyyy yyy yy y MMMM MMM MM M LLLL LLL LL L"
" dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z"; + " dddd ddd dd d DDDD DDD DD D EEEE EEE EE E aaaa aaa aa a zzzz zzz zz z";
fdf = getInstance(pattern); fdf = getInstance(pattern);
sdf = new SimpleDateFormat(pattern); sdf = new SimpleDateFormat(pattern);
// SDF bug fix starting with Java 7 // SDF bug fix starting with Java 7
@ -279,8 +282,7 @@ public class FastDatePrinterTest extends AbstractLangTest {
} }
/** /**
* According to LANG-916 (https://issues.apache.org/jira/browse/LANG-916), * According to LANG-916 (https://issues.apache.org/jira/browse/LANG-916), the format method did contain a bug: it did not use the TimeZone data.
* the format method did contain a bug: it did not use the TimeZone data.
* *
* This method test that the bug is fixed. * This method test that the bug is fixed.
*/ */
@ -308,7 +310,7 @@ public class FastDatePrinterTest extends AbstractLangTest {
@Test @Test
public void testLocaleMatches() { public void testLocaleMatches() {
final DatePrinter printer= getInstance(YYYY_MM_DD, SWEDEN); final DatePrinter printer = getInstance(YYYY_MM_DD, SWEDEN);
assertEquals(SWEDEN, printer.getLocale()); assertEquals(SWEDEN, printer.getLocale());
} }
@ -344,7 +346,7 @@ public class FastDatePrinterTest extends AbstractLangTest {
@Test @Test
public void testPatternMatches() { public void testPatternMatches() {
final DatePrinter printer= getInstance(YYYY_MM_DD); final DatePrinter printer = getInstance(YYYY_MM_DD);
assertEquals(YYYY_MM_DD, printer.getPattern()); assertEquals(YYYY_MM_DD, printer.getPattern());
} }
@ -366,8 +368,7 @@ public class FastDatePrinterTest extends AbstractLangTest {
} }
/** /**
* testLowYearPadding showed that the date was buggy * testLowYearPadding showed that the date was buggy This test confirms it, getting 366 back as a date
* This test confirms it, getting 366 back as a date
*/ */
@Test @Test
public void testSimpleDate() { public void testSimpleDate() {
@ -421,13 +422,13 @@ public class FastDatePrinterTest extends AbstractLangTest {
@Test @Test
public void testTimeZoneMatches() { public void testTimeZoneMatches() {
final DatePrinter printer= getInstance(YYYY_MM_DD, NEW_YORK); final DatePrinter printer = getInstance(YYYY_MM_DD, NEW_YORK);
assertEquals(NEW_YORK, printer.getTimeZone()); assertEquals(NEW_YORK, printer.getTimeZone());
} }
@Test @Test
public void testToStringContainsName() { public void testToStringContainsName() {
final DatePrinter printer= getInstance(YYYY_MM_DD); final DatePrinter printer = getInstance(YYYY_MM_DD);
assertTrue(printer.toString().startsWith("FastDate")); assertTrue(printer.toString().startsWith("FastDate"));
} }

View File

@ -55,8 +55,8 @@ public class FastTimeZoneTest extends AbstractLangTest {
assertEquals(HOURS_2, FastTimeZone.getGmtTimeZone("2:00").getRawOffset()); assertEquals(HOURS_2, FastTimeZone.getGmtTimeZone("2:00").getRawOffset());
assertEquals(MINUTES_59, FastTimeZone.getGmtTimeZone("00:59").getRawOffset()); assertEquals(MINUTES_59, FastTimeZone.getGmtTimeZone("00:59").getRawOffset());
assertEquals(MINUTES_5, FastTimeZone.getGmtTimeZone("00:5").getRawOffset()); assertEquals(MINUTES_5, FastTimeZone.getGmtTimeZone("00:5").getRawOffset());
assertEquals(HOURS_23+MINUTES_59, FastTimeZone.getGmtTimeZone("23:59").getRawOffset()); assertEquals(HOURS_23 + MINUTES_59, FastTimeZone.getGmtTimeZone("23:59").getRawOffset());
assertEquals(HOURS_2+MINUTES_5, FastTimeZone.getGmtTimeZone("2:5").getRawOffset()); assertEquals(HOURS_2 + MINUTES_5, FastTimeZone.getGmtTimeZone("2:5").getRawOffset());
} }
@Test @Test
@ -65,8 +65,8 @@ public class FastTimeZoneTest extends AbstractLangTest {
assertEquals(HOURS_2, FastTimeZone.getGmtTimeZone("0200").getRawOffset()); assertEquals(HOURS_2, FastTimeZone.getGmtTimeZone("0200").getRawOffset());
assertEquals(MINUTES_59, FastTimeZone.getGmtTimeZone("0059").getRawOffset()); assertEquals(MINUTES_59, FastTimeZone.getGmtTimeZone("0059").getRawOffset());
assertEquals(MINUTES_5, FastTimeZone.getGmtTimeZone("0005").getRawOffset()); assertEquals(MINUTES_5, FastTimeZone.getGmtTimeZone("0005").getRawOffset());
assertEquals(HOURS_23+MINUTES_59, FastTimeZone.getGmtTimeZone("2359").getRawOffset()); assertEquals(HOURS_23 + MINUTES_59, FastTimeZone.getGmtTimeZone("2359").getRawOffset());
assertEquals(HOURS_2+MINUTES_5, FastTimeZone.getGmtTimeZone("0205").getRawOffset()); assertEquals(HOURS_2 + MINUTES_5, FastTimeZone.getGmtTimeZone("0205").getRawOffset());
} }
@Test @Test

View File

@ -43,7 +43,7 @@ public class ImmutablePairTest extends AbstractLangTest {
public void testBasic() { public void testBasic() {
ImmutablePair<Integer, String> oldPair = new ImmutablePair<>(0, "foo"); ImmutablePair<Integer, String> oldPair = new ImmutablePair<>(0, "foo");
ImmutablePair<Integer, String> nowPair; ImmutablePair<Integer, String> nowPair;
for (int i=0; i<4; i++) { for (int i = 0; i < 4; i++) {
nowPair = ImmutablePair.of(oldPair); nowPair = ImmutablePair.of(oldPair);
assertEquals(0, nowPair.left.intValue()); assertEquals(0, nowPair.left.intValue());
assertEquals(0, nowPair.getLeft().intValue()); assertEquals(0, nowPair.getLeft().intValue());
@ -55,7 +55,7 @@ public class ImmutablePairTest extends AbstractLangTest {
ImmutablePair<Object, String> oldPair2 = new ImmutablePair<>(null, "bar"); ImmutablePair<Object, String> oldPair2 = new ImmutablePair<>(null, "bar");
ImmutablePair<Object, String> nowPair2; ImmutablePair<Object, String> nowPair2;
for (int i=0; i<4; i++) { for (int i = 0; i < 4; i++) {
nowPair2 = ImmutablePair.of(oldPair2); nowPair2 = ImmutablePair.of(oldPair2);
assertNull(nowPair2.left); assertNull(nowPair2.left);
assertNull(nowPair2.getLeft()); assertNull(nowPair2.getLeft());

View File

@ -37,7 +37,7 @@ public class MutablePairTest extends AbstractLangTest {
public void testBasic() { public void testBasic() {
MutablePair<Integer, String> oldPair = new MutablePair<>(0, "foo"); MutablePair<Integer, String> oldPair = new MutablePair<>(0, "foo");
MutablePair<Integer, String> nowPair; MutablePair<Integer, String> nowPair;
for (int i=0; i<4; i++) { for (int i = 0; i < 4; i++) {
nowPair = MutablePair.of(oldPair); nowPair = MutablePair.of(oldPair);
assertEquals(0, nowPair.left.intValue()); assertEquals(0, nowPair.left.intValue());
assertEquals(0, nowPair.getLeft().intValue()); assertEquals(0, nowPair.getLeft().intValue());
@ -49,7 +49,7 @@ public class MutablePairTest extends AbstractLangTest {
MutablePair<Object, String> oldPair2 = new MutablePair<>(null, "bar"); MutablePair<Object, String> oldPair2 = new MutablePair<>(null, "bar");
MutablePair<Object, String> nowPair2; MutablePair<Object, String> nowPair2;
for (int i=0; i<4; i++) { for (int i = 0; i < 4; i++) {
nowPair2 = MutablePair.of(oldPair2); nowPair2 = MutablePair.of(oldPair2);
assertNull(nowPair2.left); assertNull(nowPair2.left);
assertNull(nowPair2.getLeft()); assertNull(nowPair2.getLeft());