diff --git a/build.gradle b/build.gradle index 30a85785b..d9c00f8c0 100644 --- a/build.gradle +++ b/build.gradle @@ -20,7 +20,8 @@ repositories { } dependencies { - testImplementation 'junit:junit:4.13.2' + testImplementation(platform('org.junit:junit-bom:5.10.1')) + testImplementation('org.junit.jupiter:junit-jupiter') testImplementation 'com.jayway.jsonpath:json-path:2.4.0' testImplementation 'org.mockito:mockito-core:4.2.0' } diff --git a/pom.xml b/pom.xml index 927a989b1..6d4b42085 100644 --- a/pom.xml +++ b/pom.xml @@ -58,13 +58,22 @@ https://oss.sonatype.org/content/repositories/snapshots - + + + + org.junit + junit-bom + 5.10.1 + pom + import + + + - junit - junit - 4.13.2 + org.junit.jupiter + junit-jupiter test diff --git a/src/test/java/org/json/NumberConversionUtilTest.java b/src/test/java/org/json/NumberConversionUtilTest.java index c6f07254d..ea2d4a162 100644 --- a/src/test/java/org/json/NumberConversionUtilTest.java +++ b/src/test/java/org/json/NumberConversionUtilTest.java @@ -1,173 +1,175 @@ package org.json; -import org.junit.Test; - import java.math.BigDecimal; import java.math.BigInteger; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; -public class NumberConversionUtilTest { +class NumberConversionUtilTest { @Test - public void shouldParseDecimalFractionNumbersWithMultipleLeadingZeros(){ + void shouldParseDecimalFractionNumbersWithMultipleLeadingZeros(){ Number number = NumberConversionUtil.stringToNumber("00.10d"); - assertEquals("Do not match", 0.10d, number.doubleValue(),0.0d); - assertEquals("Do not match", 0.10f, number.floatValue(),0.0f); - assertEquals("Do not match", 0, number.longValue(),0); - assertEquals("Do not match", 0, number.intValue(),0); + assertEquals(0.10d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(0.10f, number.floatValue(),0.0f,"Do not match"); + assertEquals(0, number.longValue(),0,"Do not match"); + assertEquals(0, number.intValue(),0,"Do not match"); } @Test - public void shouldParseDecimalFractionNumbersWithSingleLeadingZero(){ + void shouldParseDecimalFractionNumbersWithSingleLeadingZero(){ Number number = NumberConversionUtil.stringToNumber("0.10d"); - assertEquals("Do not match", 0.10d, number.doubleValue(),0.0d); - assertEquals("Do not match", 0.10f, number.floatValue(),0.0f); - assertEquals("Do not match", 0, number.longValue(),0); - assertEquals("Do not match", 0, number.intValue(),0); + assertEquals(0.10d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(0.10f, number.floatValue(),0.0f,"Do not match"); + assertEquals(0, number.longValue(),0,"Do not match"); + assertEquals(0, number.intValue(),0,"Do not match"); } @Test - public void shouldParseDecimalFractionNumbersWithZerosAfterDecimalPoint(){ + void shouldParseDecimalFractionNumbersWithZerosAfterDecimalPoint(){ Number number = NumberConversionUtil.stringToNumber("0.010d"); - assertEquals("Do not match", 0.010d, number.doubleValue(),0.0d); - assertEquals("Do not match", 0.010f, number.floatValue(),0.0f); - assertEquals("Do not match", 0, number.longValue(),0); - assertEquals("Do not match", 0, number.intValue(),0); + assertEquals(0.010d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(0.010f, number.floatValue(),0.0f,"Do not match"); + assertEquals(0, number.longValue(),0,"Do not match"); + assertEquals(0, number.intValue(),0,"Do not match"); } @Test - public void shouldParseMixedDecimalFractionNumbersWithMultipleLeadingZeros(){ + void shouldParseMixedDecimalFractionNumbersWithMultipleLeadingZeros(){ Number number = NumberConversionUtil.stringToNumber("00200.10d"); - assertEquals("Do not match", 200.10d, number.doubleValue(),0.0d); - assertEquals("Do not match", 200.10f, number.floatValue(),0.0f); - assertEquals("Do not match", 200, number.longValue(),0); - assertEquals("Do not match", 200, number.intValue(),0); + assertEquals(200.10d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(200.10f, number.floatValue(),0.0f,"Do not match"); + assertEquals(200, number.longValue(),0,"Do not match"); + assertEquals(200, number.intValue(),0,"Do not match"); } @Test - public void shouldParseMixedDecimalFractionNumbersWithoutLeadingZero(){ + void shouldParseMixedDecimalFractionNumbersWithoutLeadingZero(){ Number number = NumberConversionUtil.stringToNumber("200.10d"); - assertEquals("Do not match", 200.10d, number.doubleValue(),0.0d); - assertEquals("Do not match", 200.10f, number.floatValue(),0.0f); - assertEquals("Do not match", 200, number.longValue(),0); - assertEquals("Do not match", 200, number.intValue(),0); + assertEquals(200.10d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(200.10f, number.floatValue(),0.0f,"Do not match"); + assertEquals(200, number.longValue(),0,"Do not match"); + assertEquals(200, number.intValue(),0,"Do not match"); } @Test - public void shouldParseMixedDecimalFractionNumbersWithZerosAfterDecimalPoint(){ + void shouldParseMixedDecimalFractionNumbersWithZerosAfterDecimalPoint(){ Number number = NumberConversionUtil.stringToNumber("200.010d"); - assertEquals("Do not match", 200.010d, number.doubleValue(),0.0d); - assertEquals("Do not match", 200.010f, number.floatValue(),0.0f); - assertEquals("Do not match", 200, number.longValue(),0); - assertEquals("Do not match", 200, number.intValue(),0); + assertEquals(200.010d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(200.010f, number.floatValue(),0.0f,"Do not match"); + assertEquals(200, number.longValue(),0,"Do not match"); + assertEquals(200, number.intValue(),0,"Do not match"); } @Test - public void shouldParseNegativeDecimalFractionNumbersWithMultipleLeadingZeros(){ + void shouldParseNegativeDecimalFractionNumbersWithMultipleLeadingZeros(){ Number number = NumberConversionUtil.stringToNumber("-00.10d"); - assertEquals("Do not match", -0.10d, number.doubleValue(),0.0d); - assertEquals("Do not match", -0.10f, number.floatValue(),0.0f); - assertEquals("Do not match", -0, number.longValue(),0); - assertEquals("Do not match", -0, number.intValue(),0); + assertEquals(-0.10d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(-0.10f, number.floatValue(),0.0f,"Do not match"); + assertEquals(-0, number.longValue(),0,"Do not match"); + assertEquals(-0, number.intValue(),0,"Do not match"); } @Test - public void shouldParseNegativeDecimalFractionNumbersWithSingleLeadingZero(){ + void shouldParseNegativeDecimalFractionNumbersWithSingleLeadingZero(){ Number number = NumberConversionUtil.stringToNumber("-0.10d"); - assertEquals("Do not match", -0.10d, number.doubleValue(),0.0d); - assertEquals("Do not match", -0.10f, number.floatValue(),0.0f); - assertEquals("Do not match", -0, number.longValue(),0); - assertEquals("Do not match", -0, number.intValue(),0); + assertEquals(-0.10d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(-0.10f, number.floatValue(),0.0f,"Do not match"); + assertEquals(-0, number.longValue(),0,"Do not match"); + assertEquals(-0, number.intValue(),0,"Do not match"); } @Test - public void shouldParseNegativeDecimalFractionNumbersWithZerosAfterDecimalPoint(){ + void shouldParseNegativeDecimalFractionNumbersWithZerosAfterDecimalPoint(){ Number number = NumberConversionUtil.stringToNumber("-0.010d"); - assertEquals("Do not match", -0.010d, number.doubleValue(),0.0d); - assertEquals("Do not match", -0.010f, number.floatValue(),0.0f); - assertEquals("Do not match", -0, number.longValue(),0); - assertEquals("Do not match", -0, number.intValue(),0); + assertEquals(-0.010d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(-0.010f, number.floatValue(),0.0f,"Do not match"); + assertEquals(-0, number.longValue(),0,"Do not match"); + assertEquals(-0, number.intValue(),0,"Do not match"); } @Test - public void shouldParseNegativeMixedDecimalFractionNumbersWithMultipleLeadingZeros(){ + void shouldParseNegativeMixedDecimalFractionNumbersWithMultipleLeadingZeros(){ Number number = NumberConversionUtil.stringToNumber("-00200.10d"); - assertEquals("Do not match", -200.10d, number.doubleValue(),0.0d); - assertEquals("Do not match", -200.10f, number.floatValue(),0.0f); - assertEquals("Do not match", -200, number.longValue(),0); - assertEquals("Do not match", -200, number.intValue(),0); + assertEquals(-200.10d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(-200.10f, number.floatValue(),0.0f,"Do not match"); + assertEquals(-200, number.longValue(),0,"Do not match"); + assertEquals(-200, number.intValue(),0,"Do not match"); } @Test - public void shouldParseNegativeMixedDecimalFractionNumbersWithoutLeadingZero(){ + void shouldParseNegativeMixedDecimalFractionNumbersWithoutLeadingZero(){ Number number = NumberConversionUtil.stringToNumber("-200.10d"); - assertEquals("Do not match", -200.10d, number.doubleValue(),0.0d); - assertEquals("Do not match", -200.10f, number.floatValue(),0.0f); - assertEquals("Do not match", -200, number.longValue(),0); - assertEquals("Do not match", -200, number.intValue(),0); + assertEquals(-200.10d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(-200.10f, number.floatValue(),0.0f,"Do not match"); + assertEquals(-200, number.longValue(),0,"Do not match"); + assertEquals(-200, number.intValue(),0,"Do not match"); } @Test - public void shouldParseNegativeMixedDecimalFractionNumbersWithZerosAfterDecimalPoint(){ + void shouldParseNegativeMixedDecimalFractionNumbersWithZerosAfterDecimalPoint(){ Number number = NumberConversionUtil.stringToNumber("-200.010d"); - assertEquals("Do not match", -200.010d, number.doubleValue(),0.0d); - assertEquals("Do not match", -200.010f, number.floatValue(),0.0f); - assertEquals("Do not match", -200, number.longValue(),0); - assertEquals("Do not match", -200, number.intValue(),0); + assertEquals(-200.010d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(-200.010f, number.floatValue(),0.0f,"Do not match"); + assertEquals(-200, number.longValue(),0,"Do not match"); + assertEquals(-200, number.intValue(),0,"Do not match"); } @Test - public void shouldParseNumbersWithExponents(){ + void shouldParseNumbersWithExponents(){ Number number = NumberConversionUtil.stringToNumber("23.45e7"); - assertEquals("Do not match", 23.45e7d, number.doubleValue(),0.0d); - assertEquals("Do not match", 23.45e7f, number.floatValue(),0.0f); - assertEquals("Do not match", 2.345E8, number.longValue(),0); - assertEquals("Do not match", 2.345E8, number.intValue(),0); + assertEquals(23.45e7d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(23.45e7f, number.floatValue(),0.0f,"Do not match"); + assertEquals(2.345E8, number.longValue(),0,"Do not match"); + assertEquals(2.345E8, number.intValue(),0,"Do not match"); } @Test - public void shouldParseNegativeNumbersWithExponents(){ + void shouldParseNegativeNumbersWithExponents(){ Number number = NumberConversionUtil.stringToNumber("-23.45e7"); - assertEquals("Do not match", -23.45e7d, number.doubleValue(),0.0d); - assertEquals("Do not match", -23.45e7f, number.floatValue(),0.0f); - assertEquals("Do not match", -2.345E8, number.longValue(),0); - assertEquals("Do not match", -2.345E8, number.intValue(),0); + assertEquals(-23.45e7d, number.doubleValue(),0.0d,"Do not match"); + assertEquals(-23.45e7f, number.floatValue(),0.0f,"Do not match"); + assertEquals(-2.345E8, number.longValue(),0,"Do not match"); + assertEquals(-2.345E8, number.intValue(),0,"Do not match"); } @Test - public void shouldParseBigDecimal(){ + void shouldParseBigDecimal(){ Number number = NumberConversionUtil.stringToNumber("19007199254740993.35481234487103587486413587843213584"); assertTrue(number instanceof BigDecimal); } @Test - public void shouldParseBigInteger(){ + void shouldParseBigInteger(){ Number number = NumberConversionUtil.stringToNumber("1900719925474099335481234487103587486413587843213584"); assertTrue(number instanceof BigInteger); } @Test - public void shouldIdentifyPotentialNumber(){ - assertTrue("Does not identify as number", NumberConversionUtil.potentialNumber("112.123")); - assertTrue("Does not identify as number", NumberConversionUtil.potentialNumber("112e123")); - assertTrue("Does not identify as number", NumberConversionUtil.potentialNumber("-112.123")); - assertTrue("Does not identify as number", NumberConversionUtil.potentialNumber("-112e23")); - assertFalse("Does not identify as not number", NumberConversionUtil.potentialNumber("--112.123")); - assertFalse("Does not identify as not number", NumberConversionUtil.potentialNumber("-a112.123")); - assertFalse("Does not identify as not number", NumberConversionUtil.potentialNumber("a112.123")); - assertFalse("Does not identify as not number", NumberConversionUtil.potentialNumber("e112.123")); + void shouldIdentifyPotentialNumber(){ + assertTrue(NumberConversionUtil.potentialNumber("112.123"), "Does not identify as number"); + assertTrue(NumberConversionUtil.potentialNumber("112e123"), "Does not identify as number"); + assertTrue(NumberConversionUtil.potentialNumber("-112.123"), "Does not identify as number"); + assertTrue(NumberConversionUtil.potentialNumber("-112e23"), "Does not identify as number"); + assertFalse(NumberConversionUtil.potentialNumber("--112.123"), "Does not identify as not number"); + assertFalse(NumberConversionUtil.potentialNumber("-a112.123"), "Does not identify as not number"); + assertFalse(NumberConversionUtil.potentialNumber("a112.123"), "Does not identify as not number"); + assertFalse(NumberConversionUtil.potentialNumber("e112.123"), "Does not identify as not number"); } - @Test(expected = NumberFormatException.class) - public void shouldExpectExceptionWhenNumberIsNotFormatted(){ - NumberConversionUtil.stringToNumber("112.aa123"); + @Test + void shouldExpectExceptionWhenNumberIsNotFormatted(){ + assertThrows(NumberFormatException.class, () -> { + NumberConversionUtil.stringToNumber("112.aa123"); + }); } diff --git a/src/test/java/org/json/junit/CDLTest.java b/src/test/java/org/json/junit/CDLTest.java index f3364fbba..3cc275162 100644 --- a/src/test/java/org/json/junit/CDLTest.java +++ b/src/test/java/org/json/junit/CDLTest.java @@ -4,11 +4,11 @@ Public Domain. */ -import static org.junit.Assert.*; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.*; import org.json.JSONException; import org.json.JSONObject; +import org.junit.jupiter.api.Test; import org.json.JSONArray; import org.json.CDL; @@ -18,7 +18,7 @@ * reference app. To test it, strings will be converted to JSON-Java classes * and then converted back. */ -public class CDLTest { +class CDLTest { /** * String of lines where the column names are in the first row, @@ -50,10 +50,12 @@ public class CDLTest { * Attempts to create a JSONArray from a null string. * Expect a NullPointerException. */ - @Test(expected=NullPointerException.class) - public void exceptionOnNullString() { - String nullStr = null; - CDL.toJSONArray(nullStr); + @Test + void exceptionOnNullString() { + assertThrows(NullPointerException.class, () -> { + String nullStr = null; + CDL.toJSONArray(nullStr); + }); } /** @@ -61,32 +63,32 @@ public void exceptionOnNullString() { * in column title line. Expects a JSONException. */ @Test - public void unbalancedQuoteInName() { + void unbalancedQuoteInName() { String badLine = "Col1, \"Col2\nVal1, Val2"; try { CDL.toJSONArray(badLine); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Missing close quote '\"'. at 12 [character 0 line 2]", - e.getMessage()); + assertEquals("Missing close quote '\"'. at 12 [character 0 line 2]", + e.getMessage(), + "Expecting an exception message"); } } - + /** * Attempts to create a JSONArray from a string with unbalanced quotes * in value line. Expects a JSONException. */ @Test - public void unbalancedQuoteInValue() { + void unbalancedQuoteInValue() { String badLine = "Col1, Col2\n\"Val1, Val2"; try { CDL.toJSONArray(badLine); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Missing close quote '\"'. at 22 [character 11 line 2]", - e.getMessage()); + assertEquals("Missing close quote '\"'. at 22 [character 11 line 2]", + e.getMessage(), + "Expecting an exception message"); } } @@ -96,33 +98,33 @@ public void unbalancedQuoteInValue() { * in column title line. Expects a JSONException. */ @Test - public void nullInName() { + void nullInName() { String badLine = "C\0ol1, Col2\nVal1, Val2"; try { CDL.toJSONArray(badLine); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Bad character 'o' (111). at 2 [character 3 line 1]", - e.getMessage()); + assertEquals("Bad character 'o' (111). at 2 [character 3 line 1]", + e.getMessage(), + "Expecting an exception message"); } } - + /** * Attempt to create a JSONArray with unbalanced quotes and a properly escaped doubled quote. * Expects a JSONException. */ @Test - public void unbalancedEscapedQuote(){ + void unbalancedEscapedQuote(){ String badLine = "Col1, Col2\n\"Val1, \"\"Val2\"\""; try { CDL.toJSONArray(badLine); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Missing close quote '\"'. at 26 [character 15 line 2]", - e.getMessage()); + assertEquals("Missing close quote '\"'. at 26 [character 15 line 2]", + e.getMessage(), + "Expecting an exception message"); } } @@ -131,7 +133,7 @@ public void unbalancedEscapedQuote(){ * Assert that there is no error for a single escaped quote within a properly embedded quote. */ @Test - public void singleEscapedQuote(){ + void singleEscapedQuote(){ String singleEscape = "Col1, Col2\nVal1, \"\"\"Val2\""; JSONArray jsonArray = CDL.toJSONArray(singleEscape); @@ -141,13 +143,13 @@ public void singleEscapedQuote(){ assertTrue(cdlStr.contains("Val1")); assertTrue(cdlStr.contains("\"Val2")); } - + /** * Assert that there is no error for a single escaped quote within a properly * embedded quote when not the last value. */ @Test - public void singleEscapedQuoteMiddleString(){ + void singleEscapedQuoteMiddleString(){ String singleEscape = "Col1, Col2\nVal1, \"\"\"Val2\"\nVal 3,Val 4"; JSONArray jsonArray = CDL.toJSONArray(singleEscape); @@ -157,13 +159,13 @@ public void singleEscapedQuoteMiddleString(){ assertTrue(cdlStr.contains("Val1")); assertTrue(cdlStr.contains("\"Val2")); } - + /** * Attempt to create a JSONArray with an escape quote and no enclosing quotes. * Expects a JSONException. */ @Test - public void badEscapedQuote(){ + void badEscapedQuote(){ String badLine = "Col1, Col2\nVal1, \"\"Val2"; try { @@ -171,74 +173,76 @@ public void badEscapedQuote(){ fail("Expecting an exception"); } catch (JSONException e) { //System.out.println("Message" + e.getMessage()); - assertEquals("Expecting an exception message", - "Bad character 'V' (86). at 20 [character 9 line 2]", - e.getMessage()); + assertEquals("Bad character 'V' (86). at 20 [character 9 line 2]", + e.getMessage(), + "Expecting an exception message"); } } - + /** * call toString with a null array */ - @Test(expected=NullPointerException.class) - public void nullJSONArrayToString() { - CDL.toString((JSONArray)null); + @Test + void nullJSONArrayToString() { + assertThrows(NullPointerException.class, () -> { + CDL.toString((JSONArray)null); + }); } /** * Create a JSONArray from an empty string */ @Test - public void emptyString() { + void emptyString() { String emptyStr = ""; JSONArray jsonArray = CDL.toJSONArray(emptyStr); - assertTrue("CDL should return null when the input string is empty", - jsonArray == null); + assertTrue(jsonArray == null, + "CDL should return null when the input string is empty"); } /** * Create a JSONArray with only 1 row */ @Test - public void onlyColumnNames() { + void onlyColumnNames() { String columnNameStr = "col1, col2, col3"; JSONArray jsonArray = CDL.toJSONArray(columnNameStr); - assertNull("CDL should return null when only 1 row is given", - jsonArray); + assertNull(jsonArray, + "CDL should return null when only 1 row is given"); } /** * Create a JSONArray from string containing only whitespace and commas */ @Test - public void emptyLinesToJSONArray() { + void emptyLinesToJSONArray() { String str = " , , , \n , , , "; JSONArray jsonArray = CDL.toJSONArray(str); - assertNull("JSONArray should be null for no content", - jsonArray); + assertNull(jsonArray, + "JSONArray should be null for no content"); } /** * call toString with a null array */ @Test - public void emptyJSONArrayToString() { + void emptyJSONArrayToString() { JSONArray jsonArray = new JSONArray(); String str = CDL.toString(jsonArray); - assertNull("CDL should return null for toString(null)", - str); + assertNull(str, + "CDL should return null for toString(null)"); } /** * call toString with a null arrays for names and values */ @Test - public void nullJSONArraysToString() { + void nullJSONArraysToString() { String str = CDL.toString(null, null); - assertNull("CDL should return null for toString(null)", - str); + assertNull(str, + "CDL should return null for toString(null)"); } /** @@ -246,7 +250,7 @@ public void nullJSONArraysToString() { * found that would otherwise be filtered out by CDL. */ @Test - public void checkSpecialChars() { + void checkSpecialChars() { JSONArray jsonArray = new JSONArray(); JSONObject jsonObject = new JSONObject(); jsonArray.put(jsonObject); @@ -254,7 +258,7 @@ public void checkSpecialChars() { jsonObject.put("Col \r1", "V1"); // \r will be filtered from value jsonObject.put("Col 2", "V2\r"); - assertTrue("expected length should be 1",jsonArray.length() == 1); + assertEquals(1, jsonArray.length(), "expected length should be 1"); String cdlStr = CDL.toString(jsonArray); jsonObject = jsonArray.getJSONObject(0); assertTrue(cdlStr.contains("\"Col 1\"")); @@ -267,7 +271,7 @@ public void checkSpecialChars() { * Create a JSONArray from a string of lines */ @Test - public void textToJSONArray() { + void textToJSONArray() { JSONArray jsonArray = CDL.toJSONArray(this.lines); JSONArray expectedJsonArray = new JSONArray(this.expectedLines); Util.compareActualVsExpectedJsonArrays(jsonArray, expectedJsonArray); @@ -278,7 +282,7 @@ public void textToJSONArray() { * string of value lines */ @Test - public void jsonArrayToJSONArray() { + void jsonArrayToJSONArray() { String nameArrayStr = "[Col1, Col2]"; String values = "V1, V2"; JSONArray nameJSONArray = new JSONArray(nameArrayStr); @@ -292,7 +296,7 @@ public void jsonArrayToJSONArray() { * then convert to string and then back to JSONArray */ @Test - public void textToJSONArrayAndBackToString() { + void textToJSONArrayAndBackToString() { JSONArray jsonArray = CDL.toJSONArray(this.lines); String jsonStr = CDL.toString(jsonArray); JSONArray finalJsonArray = CDL.toJSONArray(jsonStr); diff --git a/src/test/java/org/json/junit/CookieListTest.java b/src/test/java/org/json/junit/CookieListTest.java index 0af96401b..cdc26d565 100644 --- a/src/test/java/org/json/junit/CookieListTest.java +++ b/src/test/java/org/json/junit/CookieListTest.java @@ -4,12 +4,12 @@ Public Domain. */ -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.util.*; import org.json.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.jayway.jsonpath.*; @@ -30,16 +30,18 @@ * 'secure' name with no associated value
* - CookieList has no special handling for attribute name/value pairs.
*/ -public class CookieListTest { +class CookieListTest { /** * Attempts to create a CookieList from a null string. * Expects a NullPointerException. */ - @Test(expected=NullPointerException.class) - public void nullCookieListException() { - String cookieStr = null; - CookieList.toJSONObject(cookieStr); + @Test + void nullCookieListException() { + assertThrows(NullPointerException.class, () -> { + String cookieStr = null; + CookieList.toJSONObject(cookieStr); + }); } /** @@ -47,7 +49,7 @@ public void nullCookieListException() { * Expects a JSONException. */ @Test - public void malFormedCookieListException() { + void malFormedCookieListException() { String cookieStr = "thisCookieHasNoEqualsChar"; try { CookieList.toJSONObject(cookieStr); @@ -56,9 +58,9 @@ public void malFormedCookieListException() { /** * Not sure of the missing char, but full string compare fails */ - assertEquals("Expecting an exception message", - "Expected '=' and instead saw '' at 25 [character 26 line 1]", - e.getMessage()); + assertEquals("Expected '=' and instead saw '' at 25 [character 26 line 1]", + e.getMessage(), + "Expecting an exception message"); } } @@ -66,7 +68,7 @@ public void malFormedCookieListException() { * Creates a CookieList from an empty string. */ @Test - public void emptyStringCookieList() { + void emptyStringCookieList() { String cookieStr = ""; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); assertTrue(jsonObject.isEmpty()); @@ -76,26 +78,26 @@ public void emptyStringCookieList() { * CookieList with the simplest cookie - a name/value pair with no delimiter. */ @Test - public void simpleCookieList() { + void simpleCookieList() { String cookieStr = "SID=31d4d96e407aad42"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("Expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 31d4d96e407aad42", "31d4d96e407aad42".equals(jsonObject.query("/SID"))); + assertEquals(1, ((Map)(JsonPath.read(doc, "$"))).size(), "Expected 1 top level item"); + assertEquals("31d4d96e407aad42", jsonObject.query("/SID"), "expected 31d4d96e407aad42"); } /** * CookieList with a single a cookie which has a name/value pair and delimiter. */ @Test - public void simpleCookieListWithDelimiter() { + void simpleCookieListWithDelimiter() { String cookieStr = "SID=31d4d96e407aad42;"; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("Expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 31d4d96e407aad42", "31d4d96e407aad42".equals(jsonObject.query("/SID"))); + assertEquals(1, ((Map)(JsonPath.read(doc, "$"))).size(), "Expected 1 top level item"); + assertEquals("31d4d96e407aad42", jsonObject.query("/SID"), "expected 31d4d96e407aad42"); } /** @@ -103,7 +105,7 @@ public void simpleCookieListWithDelimiter() { * with delimiters. */ @Test - public void multiPartCookieList() { + void multiPartCookieList() { String cookieStr = "name1=myCookieValue1; "+ " name2=myCookieValue2;"+ @@ -114,31 +116,31 @@ public void multiPartCookieList() { JSONObject jsonObject = CookieList.toJSONObject(cookieStr); // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("Expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected myCookieValue1", "myCookieValue1".equals(jsonObject.query("/name1"))); - assertTrue("expected myCookieValue2", "myCookieValue2".equals(jsonObject.query("/name2"))); - assertTrue("expected myCookieValue3", "myCookieValue3".equals(jsonObject.query("/name3"))); - assertTrue("expected myCookieValue4", "myCookieValue4".equals(jsonObject.query("/name4"))); - assertTrue("expected myCookieValue5", "myCookieValue5".equals(jsonObject.query("/name5"))); - assertTrue("expected myCookieValue6", "myCookieValue6".equals(jsonObject.query("/name6"))); + assertEquals(6, ((Map)(JsonPath.read(doc, "$"))).size(), "Expected 6 top level items"); + assertEquals("myCookieValue1", jsonObject.query("/name1"), "expected myCookieValue1"); + assertEquals("myCookieValue2", jsonObject.query("/name2"), "expected myCookieValue2"); + assertEquals("myCookieValue3", jsonObject.query("/name3"), "expected myCookieValue3"); + assertEquals("myCookieValue4", jsonObject.query("/name4"), "expected myCookieValue4"); + assertEquals("myCookieValue5", jsonObject.query("/name5"), "expected myCookieValue5"); + assertEquals("myCookieValue6", jsonObject.query("/name6"), "expected myCookieValue6"); } /** * CookieList from a JSONObject with valid key and null value */ @Test - public void convertCookieListWithNullValueToString() { + void convertCookieListWithNullValueToString() { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", JSONObject.NULL); String cookieToStr = CookieList.toString(jsonObject); - assertTrue("toString() should be empty", "".equals(cookieToStr)); + assertEquals("", cookieToStr, "toString() should be empty"); } /** * CookieList with multiple entries converted to a JSON document. */ @Test - public void convertCookieListToString() { + void convertCookieListToString() { String cookieStr = "name1=myCookieValue1; "+ " name2=myCookieValue2;"+ @@ -154,21 +156,21 @@ public void convertCookieListToString() { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("Expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected myCookieValue1", "myCookieValue1".equals(jsonObject.query("/name1"))); - assertTrue("expected myCookieValue2", "myCookieValue2".equals(jsonObject.query("/name2"))); - assertTrue("expected myCookieValue3", "myCookieValue3".equals(jsonObject.query("/name3"))); - assertTrue("expected myCookieValue4", "myCookieValue4".equals(jsonObject.query("/name4"))); - assertTrue("expected myCookieValue5", "myCookieValue5".equals(jsonObject.query("/name5"))); - assertTrue("expected myCookieValue6", "myCookieValue6".equals(jsonObject.query("/name6"))); + assertEquals(6, ((Map)(JsonPath.read(doc, "$"))).size(), "Expected 6 top level items"); + assertEquals("myCookieValue1", jsonObject.query("/name1"), "expected myCookieValue1"); + assertEquals("myCookieValue2", jsonObject.query("/name2"), "expected myCookieValue2"); + assertEquals("myCookieValue3", jsonObject.query("/name3"), "expected myCookieValue3"); + assertEquals("myCookieValue4", jsonObject.query("/name4"), "expected myCookieValue4"); + assertEquals("myCookieValue5", jsonObject.query("/name5"), "expected myCookieValue5"); + assertEquals("myCookieValue6", jsonObject.query("/name6"), "expected myCookieValue6"); } /** * CookieList with multiple entries and some '+' chars and URL-encoded * values converted to a JSON document. */ - @Test - public void convertEncodedCookieListToString() { + @Test + void convertEncodedCookieListToString() { String cookieStr = "name1=myCookieValue1; "+ " name2=my+Cookie+Value+2;"+ @@ -179,12 +181,12 @@ public void convertEncodedCookieListToString() { JSONObject jsonObject = CookieList.toJSONObject(cookieStr); // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("Expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected myCookieValue1", "myCookieValue1".equals(jsonObject.query("/name1"))); - assertTrue("expected my Cookie Value 2", "my Cookie Value 2".equals(jsonObject.query("/name2"))); - assertTrue("expected my+Cookie&Value;3=", "my+Cookie&Value;3=".equals(jsonObject.query("/name3"))); - assertTrue("expected my%CookieValue4", "my%CookieValue4".equals(jsonObject.query("/name4"))); - assertTrue("expected my%CookieValue5", "myCookieValue5".equals(jsonObject.query("/name5"))); - assertTrue("expected myCookieValue6", "myCookieValue6".equals(jsonObject.query("/name6"))); + assertEquals(6, ((Map)(JsonPath.read(doc, "$"))).size(), "Expected 6 top level items"); + assertEquals("myCookieValue1", jsonObject.query("/name1"), "expected myCookieValue1"); + assertEquals("my Cookie Value 2", jsonObject.query("/name2"), "expected my Cookie Value 2"); + assertEquals("my+Cookie&Value;3=", jsonObject.query("/name3"), "expected my+Cookie&Value;3="); + assertEquals("my%CookieValue4", jsonObject.query("/name4"), "expected my%CookieValue4"); + assertEquals("myCookieValue5", jsonObject.query("/name5"), "expected my%CookieValue5"); + assertEquals("myCookieValue6", jsonObject.query("/name6"), "expected myCookieValue6"); } } diff --git a/src/test/java/org/json/junit/CookieTest.java b/src/test/java/org/json/junit/CookieTest.java index edd8a7eeb..107486fab 100644 --- a/src/test/java/org/json/junit/CookieTest.java +++ b/src/test/java/org/json/junit/CookieTest.java @@ -4,10 +4,10 @@ Public Domain. */ -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.json.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** @@ -23,16 +23,18 @@ *

* A JSON-Java encoded cookie escapes '+', '%', '=', ';' with %hh values. */ -public class CookieTest { +class CookieTest { /** * Attempts to create a JSONObject from a null string. * Expects a NullPointerException. */ - @Test(expected=NullPointerException.class) - public void nullCookieException() { - String cookieStr = null; - Cookie.toJSONObject(cookieStr); + @Test + void nullCookieException() { + assertThrows(NullPointerException.class, () -> { + String cookieStr = null; + Cookie.toJSONObject(cookieStr); + }); } /** @@ -41,15 +43,15 @@ public void nullCookieException() { * Expects a JSONException. */ @Test - public void malFormedNameValueException() { + void malFormedNameValueException() { String cookieStr = "thisCookieHasNoEqualsChar"; try { Cookie.toJSONObject(cookieStr); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Expected '=' and instead saw '' at 25 [character 26 line 1]", - e.getMessage()); + assertEquals("Expected '=' and instead saw '' at 25 [character 26 line 1]", + e.getMessage(), + "Expecting an exception message"); } } @@ -59,12 +61,12 @@ public void malFormedNameValueException() { * Expects a JSONException. */ @Test - public void booleanAttribute() { + void booleanAttribute() { String cookieStr = "this=Cookie;myAttribute"; JSONObject jo = Cookie.toJSONObject(cookieStr); - assertTrue("has key 'name'", jo.has("name")); - assertTrue("has key 'value'", jo.has("value")); - assertTrue("has key 'myAttribute'", jo.has("myattribute")); + assertTrue(jo.has("name"), "has key 'name'"); + assertTrue(jo.has("value"), "has key 'value'"); + assertTrue(jo.has("myattribute"), "has key 'myAttribute'"); } /** @@ -73,17 +75,18 @@ public void booleanAttribute() { * Expects a JSONException */ @Test - public void emptyStringCookieException() { + void emptyStringCookieException() { String cookieStr = ""; try { Cookie.toJSONObject(cookieStr); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Cookies must have a 'name'", - e.getMessage()); + assertEquals("Cookies must have a 'name'", + e.getMessage(), + "Expecting an exception message"); } } + /** * * Attempts to create a JSONObject from an cookie string where the name is blank.
@@ -91,15 +94,15 @@ public void emptyStringCookieException() { * Expects a JSONException */ @Test - public void emptyNameCookieException() { + void emptyNameCookieException() { String cookieStr = " = value "; try { Cookie.toJSONObject(cookieStr); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Cookies must have a 'name'", - e.getMessage()); + assertEquals("Cookies must have a 'name'", + e.getMessage(), + "Expecting an exception message"); } } @@ -107,7 +110,7 @@ public void emptyNameCookieException() { * Cookie from a simple name/value pair with no delimiter */ @Test - public void simpleCookie() { + void simpleCookie() { String cookieStr = "SID=31d4d96e407aad42"; String expectedCookieStr = "{\"name\":\"SID\",\"value\":\"31d4d96e407aad42\"}"; JSONObject jsonObject = Cookie.toJSONObject(cookieStr); @@ -121,7 +124,7 @@ public void simpleCookie() { * as a boolean. */ @Test - public void multiPartCookie() { + void multiPartCookie() { String cookieStr = "PH=deleted; "+ " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ @@ -148,7 +151,7 @@ public void multiPartCookie() { * This test confirms both behaviors. */ @Test - public void convertCookieToString() { + void convertCookieToString() { String cookieStr = "PH=deleted; "+ " expires=Wed, 19-Mar-2014 17:53:53 GMT;"+ @@ -188,7 +191,7 @@ public void convertCookieToString() { * behavior. */ @Test - public void convertEncodedCookieToString() { + void convertEncodedCookieToString() { String cookieStr = "PH=deleted; "+ " expires=Wed,+19-Mar-2014+17:53:53+GMT;"+ @@ -209,7 +212,7 @@ public void convertEncodedCookieToString() { Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); Util.compareActualVsExpectedJsonObjects(finalJsonObject,expectedJsonObject); } - + /** * A public API method performs a URL encoding for selected chars * in a string. Control chars, '+', '%', '=', ';' are all encoded @@ -217,12 +220,12 @@ public void convertEncodedCookieToString() { * This test confirms that behavior. */ @Test - public void escapeString() { + void escapeString() { String str = " +%\r\n\t\b%=;;; "; String expectedStr = "%2b%25%0d%0a%09%08%25%3d%3b%3b%3b"; String actualStr = Cookie.escape(str); - assertTrue("expect escape() to encode correctly. Actual: " +actualStr+ - " expected: " +expectedStr, expectedStr.equals(actualStr)); + assertEquals(expectedStr, actualStr, "expect escape() to encode correctly. Actual: " + actualStr + + " expected: " + expectedStr); } /** @@ -232,11 +235,11 @@ public void escapeString() { * This test confirms that behavior. */ @Test - public void unescapeString() { + void unescapeString() { String str = " +%2b%25%0d%0a%09%08%25%3d%3b%3b%3b+ "; String expectedStr = " +%\r\n\t\b%=;;; "; String actualStr = Cookie.unescape(str); - assertTrue("expect unescape() to decode correctly. Actual: " +actualStr+ - " expected: " +expectedStr, expectedStr.equals(actualStr)); + assertEquals(expectedStr, actualStr, "expect unescape() to decode correctly. Actual: " + actualStr + + " expected: " + expectedStr); } } diff --git a/src/test/java/org/json/junit/EnumTest.java b/src/test/java/org/json/junit/EnumTest.java index 1496a636a..5c16804f9 100644 --- a/src/test/java/org/json/junit/EnumTest.java +++ b/src/test/java/org/json/junit/EnumTest.java @@ -4,9 +4,7 @@ Public Domain. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; import java.util.EnumSet; import java.util.List; @@ -17,7 +15,7 @@ import org.json.junit.data.MyEnum; import org.json.junit.data.MyEnumClass; import org.json.junit.data.MyEnumField; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; @@ -27,7 +25,7 @@ * classes, all required behavior is already be present in some form. * These tests explore how enum serialization works with JSON-Java. */ -public class EnumTest { +class EnumTest { /** * To serialize an enum by its getters, use the JSONObject Object constructor. @@ -35,11 +33,11 @@ public class EnumTest { * is created whose entries are the getter name/value pairs. */ @Test - public void jsonObjectFromEnum() { + void jsonObjectFromEnum() { // If there are no getters then the object is empty. MyEnum myEnum = MyEnum.VAL2; JSONObject jsonObject = new JSONObject(myEnum); - assertTrue("simple enum has no getters", jsonObject.isEmpty()); + assertTrue(jsonObject.isEmpty(), "simple enum has no getters"); // enum with a getters should create a non-empty object MyEnumField myEnumField = MyEnumField.VAL2; @@ -48,9 +46,9 @@ public void jsonObjectFromEnum() { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonObject.toString()); - assertTrue("expecting 2 items in top level object", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expecting val 2", "val 2".equals(jsonObject.query("/value"))); - assertTrue("expecting 2", Integer.valueOf(2).equals(jsonObject.query("/intVal"))); + assertEquals(2, ((Map)(JsonPath.read(doc, "$"))).size(), "expecting 2 items in top level object"); + assertEquals("val 2", jsonObject.query("/value"), "expecting val 2"); + assertEquals(Integer.valueOf(2), jsonObject.query("/intVal"), "expecting 2"); /** * class which contains enum instances. Each enum should be stored @@ -63,12 +61,12 @@ public void jsonObjectFromEnum() { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected 2 myEnumField items", "VAL3".equals((JsonPath.read(doc, "$.myEnumField")))); - assertTrue("expected 0 myEnum items", "VAL1".equals((JsonPath.read(doc, "$.myEnum")))); + assertEquals(2, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 2 top level items"); + assertEquals("VAL3", (JsonPath.read(doc, "$.myEnumField")), "expected 2 myEnumField items"); + assertEquals("VAL1", (JsonPath.read(doc, "$.myEnum")), "expected 0 myEnum items"); - assertTrue("expecting MyEnumField.VAL3", MyEnumField.VAL3.equals(jsonObject.query("/myEnumField"))); - assertTrue("expecting MyEnum.VAL1", MyEnum.VAL1.equals(jsonObject.query("/myEnum"))); + assertEquals(MyEnumField.VAL3, jsonObject.query("/myEnumField"), "expecting MyEnumField.VAL3"); + assertEquals(MyEnum.VAL1, jsonObject.query("/myEnum"), "expecting MyEnum.VAL1"); } /** @@ -76,7 +74,7 @@ public void jsonObjectFromEnum() { * and the JSONObject Object with names constructor. */ @Test - public void jsonObjectFromEnumWithNames() { + void jsonObjectFromEnumWithNames() { String [] names; JSONObject jsonObject; @@ -87,59 +85,59 @@ public void jsonObjectFromEnumWithNames() { // validate JSON object Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected VAL1", MyEnum.VAL1.equals(jsonObject.query("/VAL1"))); - assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonObject.query("/VAL2"))); - assertTrue("expected VAL3", MyEnum.VAL3.equals(jsonObject.query("/VAL3"))); + assertEquals(3, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 3 top level items"); + assertEquals(MyEnum.VAL1, jsonObject.query("/VAL1"), "expected VAL1"); + assertEquals(MyEnum.VAL2, jsonObject.query("/VAL2"), "expected VAL2"); + assertEquals(MyEnum.VAL3, jsonObject.query("/VAL3"), "expected VAL3"); MyEnumField myEnumField = MyEnumField.VAL3; names = JSONObject.getNames(myEnumField); // The values will be MyEnmField fields jsonObject = new JSONObject(myEnumField, names); doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/VAL1"))); - assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/VAL2"))); - assertTrue("expected VAL3", MyEnumField.VAL3.equals(jsonObject.query("/VAL3"))); + assertEquals(3, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 3 top level items"); + assertEquals(MyEnumField.VAL1, jsonObject.query("/VAL1"), "expected VAL1"); + assertEquals(MyEnumField.VAL2, jsonObject.query("/VAL2"), "expected VAL2"); + assertEquals(MyEnumField.VAL3, jsonObject.query("/VAL3"), "expected VAL3"); } - + /** * Verify that enums are handled consistently between JSONArray and JSONObject */ @Test - public void verifyEnumConsistency(){ + void verifyEnumConsistency(){ JSONObject jo = new JSONObject(); jo.put("value", MyEnumField.VAL2); String expected="{\"value\":\"VAL2\"}"; String actual = jo.toString(); - assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + assertEquals(expected, actual, "Expected " + expected + " but actual was " + actual); jo.accumulate("value", MyEnumField.VAL1); expected="{\"value\":[\"VAL2\",\"VAL1\"]}"; actual = jo.toString(); - assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + assertEquals(expected, actual, "Expected " + expected + " but actual was " + actual); jo.remove("value"); jo.append("value", MyEnumField.VAL1); expected="{\"value\":[\"VAL1\"]}"; actual = jo.toString(); - assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + assertEquals(expected, actual, "Expected " + expected + " but actual was " + actual); jo.put("value", EnumSet.of(MyEnumField.VAL2)); expected="{\"value\":[\"VAL2\"]}"; actual = jo.toString(); - assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + assertEquals(expected, actual, "Expected " + expected + " but actual was " + actual); JSONArray ja = new JSONArray(); ja.put(MyEnumField.VAL2); jo.put("value", ja); actual = jo.toString(); - assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + assertEquals(expected, actual, "Expected " + expected + " but actual was " + actual); jo.put("value", new MyEnumField[]{MyEnumField.VAL2}); actual = jo.toString(); - assertTrue("Expected "+expected+" but actual was "+actual, expected.equals(actual)); + assertEquals(expected, actual, "Expected " + expected + " but actual was " + actual); } @@ -148,7 +146,7 @@ public void verifyEnumConsistency(){ * will be stored as a enum type. */ @Test - public void enumPut() { + void enumPut() { JSONObject jsonObject = new JSONObject(); MyEnum myEnum = MyEnum.VAL2; jsonObject.put("myEnum", myEnum); @@ -157,9 +155,9 @@ public void enumPut() { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level objects", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonObject.query("/myEnum"))); - assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/myEnumField"))); + assertEquals(2, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 2 top level objects"); + assertEquals(MyEnum.VAL2, jsonObject.query("/myEnum"), "expected VAL2"); + assertEquals(MyEnumField.VAL1, jsonObject.query("/myEnumField"), "expected VAL1"); JSONArray jsonArray = new JSONArray(); jsonArray.put(myEnum); @@ -167,16 +165,16 @@ public void enumPut() { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 2 top level objects", ((List)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonArray.query("/0"))); - assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonArray.query("/1"))); + assertEquals(2, ((List)(JsonPath.read(doc, "$"))).size(), "expected 2 top level objects"); + assertEquals(MyEnum.VAL2, jsonArray.query("/0"), "expected VAL2"); + assertEquals(MyEnumField.VAL1, jsonArray.query("/1"), "expected VAL1"); /** * Leaving these tests because they exercise get, opt, and remove */ - assertTrue("expecting myEnum value", MyEnum.VAL2.equals(jsonArray.get(0))); - assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.opt(1))); - assertTrue("expecting myEnumField value", MyEnumField.VAL1.equals(jsonArray.remove(1))); + assertEquals(MyEnum.VAL2, jsonArray.get(0), "expecting myEnum value"); + assertEquals(MyEnumField.VAL1, jsonArray.opt(1), "expecting myEnumField value"); + assertEquals(MyEnumField.VAL1, jsonArray.remove(1), "expecting myEnumField value"); } /** @@ -184,7 +182,7 @@ public void enumPut() { * For enums, this means the assigned value will be returned as a string. */ @Test - public void enumValueToString() { + void enumValueToString() { String expectedStr1 = "\"VAL1\""; String expectedStr2 = "\"VAL1\""; MyEnum myEnum = MyEnum.VAL1; @@ -192,11 +190,9 @@ public void enumValueToString() { MyEnumClass myEnumClass = new MyEnumClass(); String str1 = JSONObject.valueToString(myEnum); - assertTrue("actual myEnum: "+str1+" expected: "+expectedStr1, - str1.equals(expectedStr1)); + assertEquals(str1, expectedStr1, "actual myEnum: " + str1 + " expected: " + expectedStr1); String str2 = JSONObject.valueToString(myEnumField); - assertTrue("actual myEnumField: "+str2+" expected: "+expectedStr2, - str2.equals(expectedStr2)); + assertEquals(str2, expectedStr2, "actual myEnumField: " + str2 + " expected: " + expectedStr2); /** * However, an enum within another class will not be rendered @@ -206,8 +202,8 @@ public void enumValueToString() { myEnumClass.setMyEnum(MyEnum.VAL1); myEnumClass.setMyEnumField(MyEnumField.VAL1); String str3 = JSONObject.valueToString(myEnumClass); - assertTrue("actual myEnumClass: "+str3+" expected: "+expectedStr3, - str3.startsWith(expectedStr3)); + assertTrue(str3.startsWith(expectedStr3), + "actual myEnumClass: "+str3+" expected: "+expectedStr3); } /** @@ -215,20 +211,20 @@ public void enumValueToString() { * json[Object|Array].toString should serialize it in a reasonable way. */ @Test - public void enumToString() { + void enumToString() { MyEnum myEnum = MyEnum.VAL2; JSONObject jsonObject = new JSONObject(myEnum); String expectedStr = "{}"; - assertTrue("myEnum toString() should be empty", expectedStr.equals(jsonObject.toString())); + assertEquals(expectedStr, jsonObject.toString(), "myEnum toString() should be empty"); MyEnumField myEnumField = MyEnumField.VAL2; jsonObject = new JSONObject(myEnumField); // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected val 2", "val 2".equals(jsonObject.query("/value"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/intVal"))); + assertEquals(2, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 2 top level items"); + assertEquals("val 2", jsonObject.query("/value"), "expected val 2"); + assertEquals(Integer.valueOf(2), jsonObject.query("/intVal"), "expected 2"); MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); @@ -237,29 +233,29 @@ public void enumToString() { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected VAL3", "VAL3".equals((JsonPath.read(doc, "$.myEnumField")))); - assertTrue("expected VAL1", "VAL1".equals((JsonPath.read(doc, "$.myEnum")))); + assertEquals(2, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 2 top level items"); + assertEquals("VAL3", (JsonPath.read(doc, "$.myEnumField")), "expected VAL3"); + assertEquals("VAL1", (JsonPath.read(doc, "$.myEnum")), "expected VAL1"); String [] names = JSONObject.getNames(myEnum); jsonObject = new JSONObject(myEnum, names); // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected VAL1", MyEnum.VAL1.equals(jsonObject.query("/VAL1"))); - assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonObject.query("/VAL2"))); - assertTrue("expected VAL3", MyEnum.VAL3.equals(jsonObject.query("/VAL3"))); + assertEquals(3, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 3 top level items"); + assertEquals(MyEnum.VAL1, jsonObject.query("/VAL1"), "expected VAL1"); + assertEquals(MyEnum.VAL2, jsonObject.query("/VAL2"), "expected VAL2"); + assertEquals(MyEnum.VAL3, jsonObject.query("/VAL3"), "expected VAL3"); names = JSONObject.getNames(myEnumField); jsonObject = new JSONObject(myEnumField, names); // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected VAL1", MyEnumField.VAL1.equals(jsonObject.query("/VAL1"))); - assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/VAL2"))); - assertTrue("expected VAL3", MyEnumField.VAL3.equals(jsonObject.query("/VAL3"))); + assertEquals(3, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 3 top level items"); + assertEquals(MyEnumField.VAL1, jsonObject.query("/VAL1"), "expected VAL1"); + assertEquals(MyEnumField.VAL2, jsonObject.query("/VAL2"), "expected VAL2"); + assertEquals(MyEnumField.VAL3, jsonObject.query("/VAL3"), "expected VAL3"); expectedStr = "{\"myEnum\":\"VAL2\", \"myEnumField\":\"VAL2\"}"; jsonObject = new JSONObject(); @@ -268,9 +264,9 @@ public void enumToString() { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonObject.query("/myEnum"))); - assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/myEnumField"))); + assertEquals(2, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 2 top level items"); + assertEquals(MyEnum.VAL2, jsonObject.query("/myEnum"), "expected VAL2"); + assertEquals(MyEnumField.VAL2, jsonObject.query("/myEnumField"), "expected VAL2"); JSONArray jsonArray = new JSONArray(); jsonArray.put(myEnum); @@ -278,17 +274,17 @@ public void enumToString() { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 2 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected VAL2", MyEnum.VAL2.equals(jsonArray.query("/0"))); - assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonArray.query("/1"))); + assertEquals(2, ((List)(JsonPath.read(doc, "$"))).size(), "expected 2 top level items"); + assertEquals(MyEnum.VAL2, jsonArray.query("/0"), "expected VAL2"); + assertEquals(MyEnumField.VAL2, jsonArray.query("/1"), "expected VAL2"); } /** * Wrap should handle enums exactly as a value type like Integer, Boolean, or String. */ @Test - public void wrap() { - assertTrue("simple enum has no getters", JSONObject.wrap(MyEnum.VAL2) instanceof MyEnum); + void wrap() { + assertTrue(JSONObject.wrap(MyEnum.VAL2) instanceof MyEnum, "simple enum has no getters"); MyEnumField myEnumField = MyEnumField.VAL2; JSONObject jsonObject = new JSONObject(); @@ -296,8 +292,8 @@ public void wrap() { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected VAL2", MyEnumField.VAL2.equals(jsonObject.query("/enum"))); + assertEquals(1, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 1 top level items"); + assertEquals(MyEnumField.VAL2, jsonObject.query("/enum"), "expected VAL2"); MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); @@ -306,12 +302,12 @@ public void wrap() { // validate JSON content doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected VAL3", "VAL3".equals((JsonPath.read(doc, "$.myEnumField")))); - assertTrue("expected VAL1", "VAL1".equals((JsonPath.read(doc, "$.myEnum")))); + assertEquals(2, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 2 top level items"); + assertEquals("VAL3", (JsonPath.read(doc, "$.myEnumField")), "expected VAL3"); + assertEquals("VAL1", (JsonPath.read(doc, "$.myEnum")), "expected VAL1"); - assertTrue("expecting MyEnumField.VAL3", MyEnumField.VAL3.equals(jsonObject.query("/myEnumField"))); - assertTrue("expecting MyEnum.VAL1", MyEnum.VAL1.equals(jsonObject.query("/myEnum"))); + assertEquals(MyEnumField.VAL3, jsonObject.query("/myEnumField"), "expecting MyEnumField.VAL3"); + assertEquals(MyEnum.VAL1, jsonObject.query("/myEnum"), "expecting MyEnum.VAL1"); } /** @@ -327,7 +323,7 @@ public void wrap() { * Exercise these enum API methods on JSONObject and JSONArray */ @Test - public void enumAPI() { + void enumAPI() { MyEnumClass myEnumClass = new MyEnumClass(); myEnumClass.setMyEnum(MyEnum.VAL1); MyEnumField myEnumField = MyEnumField.VAL2; @@ -340,37 +336,37 @@ public void enumAPI() { // get a plain old enum MyEnumField actualEnum = jsonObject.getEnum(MyEnumField.class, "enumKey"); - assertTrue("get myEnumField", actualEnum == MyEnumField.VAL2); + assertTrue(actualEnum == MyEnumField.VAL2, "get myEnumField"); // try to get the wrong value try { actualEnum = jsonObject.getEnum(MyEnumField.class, "strKey"); - assertTrue("should throw an exception for wrong key", false); + assertTrue(false, "should throw an exception for wrong key"); } catch (Exception ignored) {} // get a class that contains an enum MyEnumClass actualEnumClass = (MyEnumClass)jsonObject.get("enumClassKey"); - assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1); + assertTrue(actualEnumClass.getMyEnum() == MyEnum.VAL1, "get enum"); // opt a plain old enum actualEnum = jsonObject.optEnum(MyEnumField.class, "enumKey"); - assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2); + assertTrue(actualEnum == MyEnumField.VAL2, "opt myEnumField"); // opt the wrong value actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey"); - assertTrue("opt null", actualEnum == null); + assertTrue(actualEnum == null, "opt null"); // opt a class that contains an enum actualEnumClass = (MyEnumClass)jsonObject.opt("enumClassKey"); - assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1); + assertTrue(actualEnumClass.getMyEnum() == MyEnum.VAL1, "get enum"); // opt with default a plain old enum actualEnum = jsonObject.optEnum(MyEnumField.class, "enumKey", null); - assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2); + assertTrue(actualEnum == MyEnumField.VAL2, "opt myEnumField"); // opt with default the wrong value actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey", null); - assertNull("opt null", actualEnum); + assertNull(actualEnum, "opt null"); // opt with default the string value actualEnum = jsonObject.optEnum(MyEnumField.class, "strKey2", null); @@ -378,10 +374,10 @@ public void enumAPI() { // opt with default an index that does not exist actualEnum = jsonObject.optEnum(MyEnumField.class, "noKey", null); - assertNull("opt null", actualEnum); + assertNull(actualEnum, "opt null"); - assertNull("Expected Null when the enum class is null", - jsonObject.optEnum(null, "enumKey")); + assertNull(jsonObject.optEnum(null, "enumKey"), + "Expected Null when the enum class is null"); /** * Exercise the proposed enum API methods on JSONArray @@ -393,41 +389,41 @@ public void enumAPI() { // get a plain old enum actualEnum = jsonArray.getEnum(MyEnumField.class, 1); - assertTrue("get myEnumField", actualEnum == MyEnumField.VAL2); + assertTrue(actualEnum == MyEnumField.VAL2, "get myEnumField"); // try to get the wrong value try { actualEnum = jsonArray.getEnum(MyEnumField.class, 0); - assertTrue("should throw an exception for wrong index", false); + assertTrue(false, "should throw an exception for wrong index"); } catch (Exception ignored) {} // get a class that contains an enum actualEnumClass = (MyEnumClass)jsonArray.get(2); - assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1); + assertTrue(actualEnumClass.getMyEnum() == MyEnum.VAL1, "get enum"); // opt a plain old enum actualEnum = jsonArray.optEnum(MyEnumField.class, 1); - assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2); + assertTrue(actualEnum == MyEnumField.VAL2, "opt myEnumField"); // opt the wrong value actualEnum = jsonArray.optEnum(MyEnumField.class, 0); - assertTrue("opt null", actualEnum == null); + assertTrue(actualEnum == null, "opt null"); // opt a class that contains an enum actualEnumClass = (MyEnumClass)jsonArray.opt(2); - assertTrue("get enum", actualEnumClass.getMyEnum() == MyEnum.VAL1); + assertTrue(actualEnumClass.getMyEnum() == MyEnum.VAL1, "get enum"); // opt with default a plain old enum actualEnum = jsonArray.optEnum(MyEnumField.class, 1, null); - assertTrue("opt myEnumField", actualEnum == MyEnumField.VAL2); + assertTrue(actualEnum == MyEnumField.VAL2, "opt myEnumField"); // opt with default the wrong value actualEnum = jsonArray.optEnum(MyEnumField.class, 0, null); - assertTrue("opt null", actualEnum == null); + assertTrue(actualEnum == null, "opt null"); // opt with default an index that does not exist actualEnum = jsonArray.optEnum(MyEnumField.class, 3, null); - assertTrue("opt null", actualEnum == null); + assertTrue(actualEnum == null, "opt null"); } } diff --git a/src/test/java/org/json/junit/HTTPTest.java b/src/test/java/org/json/junit/HTTPTest.java index 703d5ad2f..55443b399 100644 --- a/src/test/java/org/json/junit/HTTPTest.java +++ b/src/test/java/org/json/junit/HTTPTest.java @@ -4,25 +4,27 @@ Public Domain. */ -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.json.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Unit tests for JSON-Java HTTP.java. See RFC7230. */ -public class HTTPTest { +class HTTPTest { /** * Attempt to call HTTP.toJSONObject() with a null string * Expects a NUllPointerException. */ - @Test(expected=NullPointerException.class) - public void nullHTTPException() { - String httpStr = null; - HTTP.toJSONObject(httpStr); + @Test + void nullHTTPException() { + assertThrows(NullPointerException.class, () -> { + String httpStr = null; + HTTP.toJSONObject(httpStr); + }); } /** @@ -30,15 +32,14 @@ public void nullHTTPException() { * an empty object. Expects a JSONException. */ @Test - public void notEnoughHTTPException() { + void notEnoughHTTPException() { String httpStr = "{}"; JSONObject jsonObject = new JSONObject(httpStr); try { HTTP.toString(jsonObject); - assertTrue("Expected to throw exception", false); + assertTrue(false, "Expected to throw exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Not enough material for an HTTP header.".equals(e.getMessage())); + assertEquals("Not enough material for an HTTP header.", e.getMessage(), "Expecting an exception message"); } } @@ -48,7 +49,7 @@ public void notEnoughHTTPException() { * and HTTP-Version. */ @Test - public void emptyStringHTTPRequest() { + void emptyStringHTTPRequest() { String httpStr = ""; String expectedHTTPStr = "{\"Request-URI\":\"\",\"Method\":\"\",\"HTTP-Version\":\"\"}"; JSONObject jsonObject = HTTP.toJSONObject(httpStr); @@ -61,7 +62,7 @@ public void emptyStringHTTPRequest() { * and HTTP-Version. */ @Test - public void simpleHTTPRequest() { + void simpleHTTPRequest() { String httpStr = "GET /hello.txt HTTP/1.1"; String expectedHTTPStr = "{\"Request-URI\":\"/hello.txt\",\"Method\":\"GET\",\"HTTP-Version\":\"HTTP/1.1\"}"; @@ -75,7 +76,7 @@ public void simpleHTTPRequest() { * HTTP-Version, Status-Code, and Reason. */ @Test - public void simpleHTTPResponse() { + void simpleHTTPResponse() { String httpStr = "HTTP/1.1 200 OK"; String expectedHTTPStr = "{\"HTTP-Version\":\"HTTP/1.1\",\"Status-Code\":\"200\",\"Reason-Phrase\":\"OK\"}"; @@ -89,7 +90,7 @@ public void simpleHTTPResponse() { * request headers. */ @Test - public void extendedHTTPRequest() { + void extendedHTTPRequest() { String httpStr = "POST /enlighten/calais.asmx HTTP/1.1\n"+ "Host: api.opencalais.com\n"+ @@ -119,7 +120,7 @@ public void extendedHTTPRequest() { * response headers. */ @Test - public void extendedHTTPResponse() { + void extendedHTTPResponse() { String httpStr = "HTTP/1.1 200 OK\n"+ "Content-Type: text/xml; charset=utf-8\n"+ @@ -140,7 +141,7 @@ public void extendedHTTPResponse() { * response headers, then convert it back into an HTTP string. */ @Test - public void convertHTTPRequestToString() { + void convertHTTPRequestToString() { String httpStr = "POST /enlighten/calais.asmx HTTP/1.1\n"+ "Host: api.opencalais.com\n"+ @@ -173,7 +174,7 @@ public void convertHTTPRequestToString() { * response headers, then convert it back into an HTTP string. */ @Test - public void convertHTTPResponseToString() { + void convertHTTPResponseToString() { String httpStr = "HTTP/1.1 200 OK\n"+ "Content-Type: text/xml; charset=utf-8\n"+ diff --git a/src/test/java/org/json/junit/JSONArrayTest.java b/src/test/java/org/json/junit/JSONArrayTest.java index fd0137978..68f7460ec 100644 --- a/src/test/java/org/json/junit/JSONArrayTest.java +++ b/src/test/java/org/json/junit/JSONArrayTest.java @@ -4,12 +4,7 @@ Public Domain. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.io.IOException; import java.io.InputStream; @@ -34,8 +29,8 @@ import org.json.JSONTokener; import org.json.ParserConfiguration; import org.json.junit.data.MyJsonString; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; @@ -73,7 +68,7 @@ public class JSONArrayTest { * Tests that the similar method is working as expected. */ @Test - public void verifySimilar() { + void verifySimilar() { final String string1 = "HasSameRef"; final String string2 = "HasDifferentRef"; JSONArray obj1 = new JSONArray() @@ -101,19 +96,21 @@ public void verifySimilar() { .put(2.0) .put(new String(string2)); - assertFalse("obj1-obj2 Should eval to false", obj1.similar(obj2)); - assertTrue("obj1-obj3 Should eval to true", obj1.similar(obj3)); - assertFalse("obj4-obj5 Should eval to false", obj4.similar(obj5)); + assertFalse(obj1.similar(obj2), "obj1-obj2 Should eval to false"); + assertTrue(obj1.similar(obj3), "obj1-obj3 Should eval to true"); + assertFalse(obj4.similar(obj5), "obj4-obj5 Should eval to false"); } - + /** * Attempt to create a JSONArray with a null string. * Expects a NullPointerException. */ - @Test(expected=NullPointerException.class) - public void nullException() { - String str = null; - assertNull("Should throw an exception", new JSONArray(str)); + @Test + void nullException() { + assertThrows(NullPointerException.class, () -> { + String str = null; + assertNull(new JSONArray(str), "Should throw an exception"); + }); } /** @@ -121,59 +118,59 @@ public void nullException() { * Expects a JSONException. */ @Test - public void emptyStr() { + void emptyStr() { String str = ""; try { - assertNull("Should throw an exception", new JSONArray(str)); + assertNull(new JSONArray(str), "Should throw an exception"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "A JSONArray text must start with '[' at 0 [character 1 line 1]", - e.getMessage()); + assertEquals("A JSONArray text must start with '[' at 0 [character 1 line 1]", + e.getMessage(), + "Expected an exception message"); } } - + /** * Attempt to create a JSONArray with an unclosed array. * Expects an exception */ @Test - public void unclosedArray() { + void unclosedArray() { try { - assertNull("Should throw an exception", new JSONArray("[")); + assertNull(new JSONArray("["), "Should throw an exception"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "Expected a ',' or ']' at 1 [character 2 line 1]", - e.getMessage()); + assertEquals("Expected a ',' or ']' at 1 [character 2 line 1]", + e.getMessage(), + "Expected an exception message"); } } - + /** * Attempt to create a JSONArray with an unclosed array. * Expects an exception */ @Test - public void unclosedArray2() { + void unclosedArray2() { try { - assertNull("Should throw an exception", new JSONArray("[\"test\"")); + assertNull(new JSONArray("[\"test\""), "Should throw an exception"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "Expected a ',' or ']' at 7 [character 8 line 1]", - e.getMessage()); + assertEquals("Expected a ',' or ']' at 7 [character 8 line 1]", + e.getMessage(), + "Expected an exception message"); } } - + /** * Attempt to create a JSONArray with an unclosed array. * Expects an exception */ @Test - public void unclosedArray3() { + void unclosedArray3() { try { - assertNull("Should throw an exception", new JSONArray("[\"test\",")); + assertNull(new JSONArray("[\"test\","), "Should throw an exception"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "Expected a ',' or ']' at 8 [character 9 line 1]", - e.getMessage()); + assertEquals("Expected a ',' or ']' at 8 [character 9 line 1]", + e.getMessage(), + "Expected an exception message"); } } @@ -183,22 +180,20 @@ public void unclosedArray3() { * Expects a JSONException. */ @Test - public void badObject() { + void badObject() { String str = "abc"; try { - assertNull("Should throw an exception", new JSONArray((Object)str)); + assertNull(new JSONArray((Object)str), "Should throw an exception"); } catch (JSONException e) { - assertTrue("Expected an exception message", - "JSONArray initial value should be a string or collection or array.". - equals(e.getMessage())); + assertEquals("JSONArray initial value should be a string or collection or array.", e.getMessage(), "Expected an exception message"); } } - + /** * Verifies that the constructor has backwards compatibility with RAW types pre-java5. */ @Test - public void verifyConstructor() { + void verifyConstructor() { final JSONArray expected = new JSONArray("[10]"); @@ -214,14 +209,14 @@ public void verifyConstructor() { JSONArray jaObj = new JSONArray(myCObj); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); + expected.similar(jaRaw), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaInt)); + expected.similar(jaInt), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObj)); + expected.similar(jaObj), + "The RAW Collection should give me the same as the Typed Collection"); Util.checkJSONArrayMaps(expected); Util.checkJSONArrayMaps(jaObj); Util.checkJSONArrayMaps(jaRaw); @@ -232,21 +227,21 @@ public void verifyConstructor() { * Tests consecutive calls to putAll with array and collection. */ @Test - public void verifyPutAll() { + void verifyPutAll() { final JSONArray jsonArray = new JSONArray(); // array int[] myInts = { 1, 2, 3, 4, 5 }; jsonArray.putAll(myInts); - assertEquals("int arrays lengths should be equal", - jsonArray.length(), - myInts.length); + assertEquals(jsonArray.length(), + myInts.length, + "int arrays lengths should be equal"); for (int i = 0; i < myInts.length; i++) { - assertEquals("int arrays elements should be equal", - myInts[i], - jsonArray.getInt(i)); + assertEquals(myInts[i], + jsonArray.getInt(i), + "int arrays elements should be equal"); } // collection @@ -255,14 +250,14 @@ public void verifyPutAll() { int len = myInts.length + myList.size(); - assertEquals("arrays lengths should be equal", - jsonArray.length(), - len); + assertEquals(jsonArray.length(), + len, + "arrays lengths should be equal"); for (int i = 0; i < myList.size(); i++) { - assertEquals("collection elements should be equal", - myList.get(i), - jsonArray.getString(myInts.length + i)); + assertEquals(myList.get(i), + jsonArray.getString(myInts.length + i), + "collection elements should be equal"); } Util.checkJSONArrayMaps(jsonArray); } @@ -271,7 +266,7 @@ public void verifyPutAll() { * Verifies that the put Collection has backwards compatibility with RAW types pre-java5. */ @Test - public void verifyPutCollection() { + void verifyPutCollection() { final JSONArray expected = new JSONArray("[[10]]"); @@ -290,25 +285,25 @@ public void verifyPutCollection() { jaInt.put(myCInt); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); + expected.similar(jaRaw), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObj)); + expected.similar(jaObj), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaInt)); + expected.similar(jaInt), + "The RAW Collection should give me the same as the Typed Collection"); Util.checkJSONArraysMaps(new ArrayList(Arrays.asList( jaRaw, jaObj, jaInt ))); } - + /** * Verifies that the put Map has backwards compatibility with RAW types pre-java5. */ @Test - public void verifyPutMap() { + void verifyPutMap() { final JSONArray expected = new JSONArray("[{\"myKey\":10}]"); @@ -333,17 +328,17 @@ public void verifyPutMap() { jaObjObj.put(myCObjObj); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); + expected.similar(jaRaw), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); + expected.similar(jaStrObj), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); + expected.similar(jaStrInt), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); + expected.similar(jaObjObj), + "The RAW Collection should give me the same as the Typed Collection"); Util.checkJSONArraysMaps(new ArrayList(Arrays.asList( expected, jaRaw, jaStrObj, jaStrInt, jaObjObj ))); @@ -355,44 +350,32 @@ public void verifyPutMap() { */ @SuppressWarnings("boxing") @Test - public void getArrayValues() { + void getArrayValues() { JSONArray jsonArray = new JSONArray(this.arrayStr); // booleans - assertTrue("Array true", - true == jsonArray.getBoolean(0)); - assertTrue("Array false", - false == jsonArray.getBoolean(1)); - assertTrue("Array string true", - true == jsonArray.getBoolean(2)); - assertTrue("Array string false", - false == jsonArray.getBoolean(3)); + assertTrue(jsonArray.getBoolean(0), "Array true"); + assertFalse(jsonArray.getBoolean(1), "Array false"); + assertTrue(jsonArray.getBoolean(2), "Array string true"); + assertFalse(jsonArray.getBoolean(3), "Array string false"); // strings - assertTrue("Array value string", - "hello".equals(jsonArray.getString(4))); + assertEquals("hello", jsonArray.getString(4), "Array value string"); // doubles - assertTrue("Array double", - Double.valueOf(23.45e-4).equals(jsonArray.getDouble(5))); - assertTrue("Array string double", - Double.valueOf(23.45).equals(jsonArray.getDouble(6))); - assertTrue("Array double can be float", - Float.valueOf(23.45e-4f).equals(jsonArray.getFloat(5))); + assertEquals(Double.valueOf(23.45e-4), jsonArray.getDouble(5), "Array double"); + assertEquals(Double.valueOf(23.45), jsonArray.getDouble(6), "Array string double"); + assertEquals(Float.valueOf(23.45e-4f), jsonArray.getFloat(5), "Array double can be float"); // ints - assertTrue("Array value int", - Integer.valueOf(42).equals(jsonArray.getInt(7))); - assertTrue("Array value string int", - Integer.valueOf(43).equals(jsonArray.getInt(8))); + assertEquals(Integer.valueOf(42), jsonArray.getInt(7), "Array value int"); + assertEquals(Integer.valueOf(43), jsonArray.getInt(8), "Array value string int"); // nested objects JSONArray nestedJsonArray = jsonArray.getJSONArray(9); - assertTrue("Array value JSONArray", nestedJsonArray != null); + assertTrue(nestedJsonArray != null, "Array value JSONArray"); JSONObject nestedJsonObject = jsonArray.getJSONObject(10); - assertTrue("Array value JSONObject", nestedJsonObject != null); + assertTrue(nestedJsonObject != null, "Array value JSONObject"); // longs - assertTrue("Array value long", - Long.valueOf(0).equals(jsonArray.getLong(11))); - assertTrue("Array value string long", - Long.valueOf(-1).equals(jsonArray.getLong(12))); + assertEquals(Long.valueOf(0), jsonArray.getLong(11), "Array value long"); + assertEquals(Long.valueOf(-1), jsonArray.getLong(12), "Array value string long"); - assertTrue("Array value null", jsonArray.isNull(-1)); + assertTrue(jsonArray.isNull(-1), "Array value null"); Util.checkJSONArrayMaps(jsonArray); } @@ -402,63 +385,55 @@ public void getArrayValues() { * API methods result in JSONExceptions */ @Test - public void failedGetArrayValues() { + void failedGetArrayValues() { JSONArray jsonArray = new JSONArray(this.arrayStr); try { jsonArray.getBoolean(4); - assertTrue("expected getBoolean to fail", false); + assertTrue(false, "expected getBoolean to fail"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "JSONArray[4] is not a boolean (class java.lang.String : hello).",e.getMessage()); + assertEquals("JSONArray[4] is not a boolean (class java.lang.String : hello).",e.getMessage(),"Expected an exception message"); } try { jsonArray.get(-1); - assertTrue("expected get to fail", false); + assertTrue(false, "expected get to fail"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "JSONArray[-1] not found.",e.getMessage()); + assertEquals("JSONArray[-1] not found.",e.getMessage(),"Expected an exception message"); } try { jsonArray.getDouble(4); - assertTrue("expected getDouble to fail", false); + assertTrue(false, "expected getDouble to fail"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "JSONArray[4] is not a double (class java.lang.String : hello).",e.getMessage()); + assertEquals("JSONArray[4] is not a double (class java.lang.String : hello).",e.getMessage(),"Expected an exception message"); } try { jsonArray.getInt(4); - assertTrue("expected getInt to fail", false); + assertTrue(false, "expected getInt to fail"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "JSONArray[4] is not a int (class java.lang.String : hello).",e.getMessage()); + assertEquals("JSONArray[4] is not a int (class java.lang.String : hello).",e.getMessage(),"Expected an exception message"); } try { jsonArray.getJSONArray(4); - assertTrue("expected getJSONArray to fail", false); + assertTrue(false, "expected getJSONArray to fail"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "JSONArray[4] is not a JSONArray (class java.lang.String : hello).",e.getMessage()); + assertEquals("JSONArray[4] is not a JSONArray (class java.lang.String : hello).",e.getMessage(),"Expected an exception message"); } try { jsonArray.getJSONObject(4); - assertTrue("expected getJSONObject to fail", false); + assertTrue(false, "expected getJSONObject to fail"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "JSONArray[4] is not a JSONObject (class java.lang.String : hello).",e.getMessage()); + assertEquals("JSONArray[4] is not a JSONObject (class java.lang.String : hello).",e.getMessage(),"Expected an exception message"); } try { jsonArray.getLong(4); - assertTrue("expected getLong to fail", false); + assertTrue(false, "expected getLong to fail"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "JSONArray[4] is not a long (class java.lang.String : hello).",e.getMessage()); + assertEquals("JSONArray[4] is not a long (class java.lang.String : hello).",e.getMessage(),"Expected an exception message"); } try { jsonArray.getString(5); - assertTrue("expected getString to fail", false); + assertTrue(false, "expected getString to fail"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "JSONArray[5] is not a String (class java.math.BigDecimal : 0.002345).",e.getMessage()); + assertEquals("JSONArray[5] is not a String (class java.math.BigDecimal : 0.002345).",e.getMessage(),"Expected an exception message"); } Util.checkJSONArrayMaps(jsonArray); } @@ -470,7 +445,7 @@ public void failedGetArrayValues() { * conforming JSON text. */ @Test - public void unquotedText() { + void unquotedText() { String str = "[value1, something!, (parens), foo@bar.com, 23, 23+45]"; JSONArray jsonArray = new JSONArray(str); List expected = Arrays.asList("value1", "something!", "(parens)", "foo@bar.com", 23, "23+45"); @@ -483,7 +458,7 @@ public void unquotedText() { * array braces are added to the beginning and end prior to validation. */ @Test - public void join() { + void join() { JSONArray jsonArray = new JSONArray(this.arrayStr); String joinStr = jsonArray.join(","); @@ -492,39 +467,38 @@ public void join() { * Don't need to remake the JSONArray to perform the parsing */ Object doc = Configuration.defaultConfiguration().jsonProvider().parse("["+joinStr+"]"); - assertTrue("expected 13 items in top level object", ((List)(JsonPath.read(doc, "$"))).size() == 13); - assertTrue("expected true", Boolean.TRUE.equals(jsonArray.query("/0"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonArray.query("/1"))); - assertTrue("expected \"true\"", "true".equals(jsonArray.query("/2"))); - assertTrue("expected \"false\"", "false".equals(jsonArray.query("/3"))); - assertTrue("expected hello", "hello".equals(jsonArray.query("/4"))); - assertTrue("expected 0.002345", BigDecimal.valueOf(0.002345).equals(jsonArray.query("/5"))); - assertTrue("expected \"23.45\"", "23.45".equals(jsonArray.query("/6"))); - assertTrue("expected 42", Integer.valueOf(42).equals(jsonArray.query("/7"))); - assertTrue("expected \"43\"", "43".equals(jsonArray.query("/8"))); - assertTrue("expected 1 item in [9]", ((List)(JsonPath.read(doc, "$[9]"))).size() == 1); - assertTrue("expected world", "world".equals(jsonArray.query("/9/0"))); - assertTrue("expected 4 items in [10]", ((Map)(JsonPath.read(doc, "$[10]"))).size() == 4); - assertTrue("expected value1", "value1".equals(jsonArray.query("/10/key1"))); - assertTrue("expected value2", "value2".equals(jsonArray.query("/10/key2"))); - assertTrue("expected value3", "value3".equals(jsonArray.query("/10/key3"))); - assertTrue("expected value4", "value4".equals(jsonArray.query("/10/key4"))); - assertTrue("expected 0", Integer.valueOf(0).equals(jsonArray.query("/11"))); - assertTrue("expected \"-1\"", "-1".equals(jsonArray.query("/12"))); + assertEquals(13, ((List)(JsonPath.read(doc, "$"))).size(), "expected 13 items in top level object"); + assertEquals(Boolean.TRUE, jsonArray.query("/0"), "expected true"); + assertEquals(Boolean.FALSE, jsonArray.query("/1"), "expected false"); + assertEquals("true", jsonArray.query("/2"), "expected \"true\""); + assertEquals("false", jsonArray.query("/3"), "expected \"false\""); + assertEquals("hello", jsonArray.query("/4"), "expected hello"); + assertEquals(BigDecimal.valueOf(0.002345), jsonArray.query("/5"), "expected 0.002345"); + assertEquals("23.45", jsonArray.query("/6"), "expected \"23.45\""); + assertEquals(Integer.valueOf(42), jsonArray.query("/7"), "expected 42"); + assertEquals("43", jsonArray.query("/8"), "expected \"43\""); + assertEquals(1, ((List)(JsonPath.read(doc, "$[9]"))).size(), "expected 1 item in [9]"); + assertEquals("world", jsonArray.query("/9/0"), "expected world"); + assertEquals(4, ((Map)(JsonPath.read(doc, "$[10]"))).size(), "expected 4 items in [10]"); + assertEquals("value1", jsonArray.query("/10/key1"), "expected value1"); + assertEquals("value2", jsonArray.query("/10/key2"), "expected value2"); + assertEquals("value3", jsonArray.query("/10/key3"), "expected value3"); + assertEquals("value4", jsonArray.query("/10/key4"), "expected value4"); + assertEquals(Integer.valueOf(0), jsonArray.query("/11"), "expected 0"); + assertEquals("-1", jsonArray.query("/12"), "expected \"-1\""); Util.checkJSONArrayMaps(jsonArray); } /** * Confirm the JSONArray.length() method */ - @Test - public void length() { - assertTrue("expected empty JSONArray length 0", - new JSONArray().length() == 0); + @Test + void length() { + assertEquals(0, new JSONArray().length(), "expected empty JSONArray length 0"); JSONArray jsonArray = new JSONArray(this.arrayStr); - assertTrue("expected JSONArray length 13. instead found "+jsonArray.length(), jsonArray.length() == 13); + assertEquals(13, jsonArray.length(), "expected JSONArray length 13. instead found " + jsonArray.length()); JSONArray nestedJsonArray = jsonArray.getJSONArray(9); - assertTrue("expected JSONArray length 1", nestedJsonArray.length() == 1); + assertEquals(1, nestedJsonArray.length(), "expected JSONArray length 1"); Util.checkJSONArraysMaps(new ArrayList(Arrays.asList( jsonArray, nestedJsonArray ))); @@ -536,136 +510,107 @@ public void length() { * and opt[type](index, default) API methods. */ @SuppressWarnings("boxing") - @Test - public void opt() { + @Test + void opt() { JSONArray jsonArray = new JSONArray(this.arrayStr); - assertTrue("Array opt value true", - Boolean.TRUE == jsonArray.opt(0)); - assertTrue("Array opt value out of range", - null == jsonArray.opt(-1)); - - assertTrue("Array opt value out of range", - null == jsonArray.opt(jsonArray.length())); - - assertTrue("Array opt boolean", - Boolean.TRUE == jsonArray.optBoolean(0)); - assertTrue("Array opt boolean default", - Boolean.FALSE == jsonArray.optBoolean(-1, Boolean.FALSE)); - assertTrue("Array opt boolean implicit default", - Boolean.FALSE == jsonArray.optBoolean(-1)); - - assertTrue("Array opt boolean object", - Boolean.TRUE.equals(jsonArray.optBooleanObject(0))); - assertTrue("Array opt boolean object default", - Boolean.FALSE.equals(jsonArray.optBooleanObject(-1, Boolean.FALSE))); - assertTrue("Array opt boolean object implicit default", - Boolean.FALSE.equals(jsonArray.optBooleanObject(-1))); - - assertTrue("Array opt double", - Double.valueOf(23.45e-4).equals(jsonArray.optDouble(5))); - assertTrue("Array opt double default", - Double.valueOf(1).equals(jsonArray.optDouble(0, 1))); - assertTrue("Array opt double default implicit", - Double.valueOf(jsonArray.optDouble(99)).isNaN()); - - assertTrue("Array opt double object", - Double.valueOf(23.45e-4).equals(jsonArray.optDoubleObject(5))); - assertTrue("Array opt double object default", - Double.valueOf(1).equals(jsonArray.optDoubleObject(0, 1D))); - assertTrue("Array opt double object default implicit", - jsonArray.optDoubleObject(99).isNaN()); - - assertTrue("Array opt float", - Float.valueOf(Double.valueOf(23.45e-4).floatValue()).equals(jsonArray.optFloat(5))); - assertTrue("Array opt float default", - Float.valueOf(1).equals(jsonArray.optFloat(0, 1))); - assertTrue("Array opt float default implicit", - Float.valueOf(jsonArray.optFloat(99)).isNaN()); - - assertTrue("Array opt float object", - Float.valueOf(23.45e-4F).equals(jsonArray.optFloatObject(5))); - assertTrue("Array opt float object default", - Float.valueOf(1).equals(jsonArray.optFloatObject(0, 1F))); - assertTrue("Array opt float object default implicit", - jsonArray.optFloatObject(99).isNaN()); - - assertTrue("Array opt Number", - BigDecimal.valueOf(23.45e-4).equals(jsonArray.optNumber(5))); - assertTrue("Array opt Number default", - Double.valueOf(1).equals(jsonArray.optNumber(0, 1d))); - assertTrue("Array opt Number default implicit", - Double.valueOf(jsonArray.optNumber(99,Double.NaN).doubleValue()).isNaN()); - - assertTrue("Array opt int", - Integer.valueOf(42).equals(jsonArray.optInt(7))); - assertTrue("Array opt int default", - Integer.valueOf(-1).equals(jsonArray.optInt(0, -1))); - assertTrue("Array opt int default implicit", - 0 == jsonArray.optInt(0)); - - assertTrue("Array opt int object", - Integer.valueOf(42).equals(jsonArray.optIntegerObject(7))); - assertTrue("Array opt int object default", - Integer.valueOf(-1).equals(jsonArray.optIntegerObject(0, -1))); - assertTrue("Array opt int object default implicit", - Integer.valueOf(0).equals(jsonArray.optIntegerObject(0))); + assertTrue(Boolean.TRUE == jsonArray.opt(0), + "Array opt value true"); + assertTrue(null == jsonArray.opt(-1), + "Array opt value out of range"); + + assertTrue(null == jsonArray.opt(jsonArray.length()), + "Array opt value out of range"); + + assertTrue(Boolean.TRUE == jsonArray.optBoolean(0), + "Array opt boolean"); + assertTrue(Boolean.FALSE == jsonArray.optBoolean(-1, Boolean.FALSE), + "Array opt boolean default"); + assertTrue(Boolean.FALSE == jsonArray.optBoolean(-1), + "Array opt boolean implicit default"); + + assertEquals(Boolean.TRUE, jsonArray.optBooleanObject(0), "Array opt boolean object"); + assertEquals(Boolean.FALSE, jsonArray.optBooleanObject(-1, Boolean.FALSE), "Array opt boolean object default"); + assertEquals(Boolean.FALSE, jsonArray.optBooleanObject(-1), "Array opt boolean object implicit default"); + + assertEquals(Double.valueOf(23.45e-4), jsonArray.optDouble(5), "Array opt double"); + assertEquals(Double.valueOf(1), jsonArray.optDouble(0, 1), "Array opt double default"); + assertTrue(Double.valueOf(jsonArray.optDouble(99)).isNaN(), + "Array opt double default implicit"); + + assertEquals(Double.valueOf(23.45e-4), jsonArray.optDoubleObject(5), "Array opt double object"); + assertEquals(Double.valueOf(1), jsonArray.optDoubleObject(0, 1D), "Array opt double object default"); + assertTrue(jsonArray.optDoubleObject(99).isNaN(), + "Array opt double object default implicit"); + + assertEquals(Float.valueOf(Double.valueOf(23.45e-4).floatValue()), jsonArray.optFloat(5), "Array opt float"); + assertEquals(Float.valueOf(1), jsonArray.optFloat(0, 1), "Array opt float default"); + assertTrue(Float.valueOf(jsonArray.optFloat(99)).isNaN(), + "Array opt float default implicit"); + + assertEquals(Float.valueOf(23.45e-4F), jsonArray.optFloatObject(5), "Array opt float object"); + assertEquals(Float.valueOf(1), jsonArray.optFloatObject(0, 1F), "Array opt float object default"); + assertTrue(jsonArray.optFloatObject(99).isNaN(), + "Array opt float object default implicit"); + + assertEquals(BigDecimal.valueOf(23.45e-4), jsonArray.optNumber(5), "Array opt Number"); + assertEquals(Double.valueOf(1), jsonArray.optNumber(0, 1d), "Array opt Number default"); + assertTrue(Double.valueOf(jsonArray.optNumber(99,Double.NaN).doubleValue()).isNaN(), + "Array opt Number default implicit"); + + assertEquals(Integer.valueOf(42), jsonArray.optInt(7), "Array opt int"); + assertEquals(Integer.valueOf(-1), jsonArray.optInt(0, -1), "Array opt int default"); + assertEquals(0, jsonArray.optInt(0), "Array opt int default implicit"); + + assertEquals(Integer.valueOf(42), jsonArray.optIntegerObject(7), "Array opt int object"); + assertEquals(Integer.valueOf(-1), jsonArray.optIntegerObject(0, -1), "Array opt int object default"); + assertEquals(Integer.valueOf(0), jsonArray.optIntegerObject(0), "Array opt int object default implicit"); JSONArray nestedJsonArray = jsonArray.optJSONArray(9); - assertTrue("Array opt JSONArray", nestedJsonArray != null); - assertTrue("Array opt JSONArray null", - null == jsonArray.optJSONArray(99)); - assertTrue("Array opt JSONArray default", - "value".equals(jsonArray.optJSONArray(99, new JSONArray("[\"value\"]")).getString(0))); + assertTrue(nestedJsonArray != null, "Array opt JSONArray"); + assertTrue(null == jsonArray.optJSONArray(99), + "Array opt JSONArray null"); + assertEquals("value", jsonArray.optJSONArray(99, new JSONArray("[\"value\"]")).getString(0), "Array opt JSONArray default"); JSONObject nestedJsonObject = jsonArray.optJSONObject(10); - assertTrue("Array opt JSONObject", nestedJsonObject != null); - assertTrue("Array opt JSONObject null", - null == jsonArray.optJSONObject(99)); - assertTrue("Array opt JSONObject default", - "value".equals(jsonArray.optJSONObject(99, new JSONObject("{\"key\":\"value\"}")).getString("key"))); - - assertTrue("Array opt long", - 0 == jsonArray.optLong(11)); - assertTrue("Array opt long default", - -2 == jsonArray.optLong(-1, -2)); - assertTrue("Array opt long default implicit", - 0 == jsonArray.optLong(-1)); - - assertTrue("Array opt long object", - Long.valueOf(0).equals(jsonArray.optLongObject(11))); - assertTrue("Array opt long object default", - Long.valueOf(-2).equals(jsonArray.optLongObject(-1, -2L))); - assertTrue("Array opt long object default implicit", - Long.valueOf(0).equals(jsonArray.optLongObject(-1))); - - assertTrue("Array opt string", - "hello".equals(jsonArray.optString(4))); - assertTrue("Array opt string default implicit", - "".equals(jsonArray.optString(-1))); + assertTrue(nestedJsonObject != null, "Array opt JSONObject"); + assertTrue(null == jsonArray.optJSONObject(99), + "Array opt JSONObject null"); + assertEquals("value", jsonArray.optJSONObject(99, new JSONObject("{\"key\":\"value\"}")).getString("key"), "Array opt JSONObject default"); + + assertEquals(0, jsonArray.optLong(11), "Array opt long"); + assertEquals(-2, jsonArray.optLong(-1, -2), "Array opt long default"); + assertEquals(0, jsonArray.optLong(-1), "Array opt long default implicit"); + + assertEquals(Long.valueOf(0), jsonArray.optLongObject(11), "Array opt long object"); + assertEquals(Long.valueOf(-2), jsonArray.optLongObject(-1, -2L), "Array opt long object default"); + assertEquals(Long.valueOf(0), jsonArray.optLongObject(-1), "Array opt long object default implicit"); + + assertEquals("hello", jsonArray.optString(4), "Array opt string"); + assertEquals("", jsonArray.optString(-1), "Array opt string default implicit"); Util.checkJSONArraysMaps(new ArrayList(Arrays.asList( jsonArray, nestedJsonArray ))); Util.checkJSONObjectMaps(nestedJsonObject); } - + /** * Verifies that the opt methods properly convert string values. */ @Test - public void optStringConversion(){ + void optStringConversion(){ JSONArray ja = new JSONArray("[\"123\",\"true\",\"false\"]"); - assertTrue("unexpected optBoolean value",ja.optBoolean(1,false)==true); - assertTrue("unexpected optBooleanObject value",Boolean.valueOf(true).equals(ja.optBooleanObject(1,false))); - assertTrue("unexpected optBoolean value",ja.optBoolean(2,true)==false); - assertTrue("unexpected optBooleanObject value",Boolean.valueOf(false).equals(ja.optBooleanObject(2,true))); - assertTrue("unexpected optInt value",ja.optInt(0,0)==123); - assertTrue("unexpected optIntegerObject value",Integer.valueOf(123).equals(ja.optIntegerObject(0,0))); - assertTrue("unexpected optLong value",ja.optLong(0,0)==123); - assertTrue("unexpected optLongObject value",Long.valueOf(123).equals(ja.optLongObject(0,0L))); - assertTrue("unexpected optDouble value",ja.optDouble(0,0.0)==123.0); - assertTrue("unexpected optDoubleObject value",Double.valueOf(123.0).equals(ja.optDoubleObject(0,0.0))); - assertTrue("unexpected optBigInteger value",ja.optBigInteger(0,BigInteger.ZERO).compareTo(new BigInteger("123"))==0); - assertTrue("unexpected optBigDecimal value",ja.optBigDecimal(0,BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); + assertTrue(ja.optBoolean(1, false), "unexpected optBoolean value"); + assertEquals(Boolean.valueOf(true), ja.optBooleanObject(1, false), "unexpected optBooleanObject value"); + assertFalse(ja.optBoolean(2, true), "unexpected optBoolean value"); + assertEquals(Boolean.valueOf(false), ja.optBooleanObject(2, true), "unexpected optBooleanObject value"); + assertEquals(123, ja.optInt(0, 0), "unexpected optInt value"); + assertEquals(Integer.valueOf(123), ja.optIntegerObject(0, 0), "unexpected optIntegerObject value"); + assertEquals(123, ja.optLong(0, 0), "unexpected optLong value"); + assertEquals(Long.valueOf(123), ja.optLongObject(0, 0L), "unexpected optLongObject value"); + assertEquals(123.0, ja.optDouble(0, 0.0), "unexpected optDouble value"); + assertEquals(Double.valueOf(123.0), ja.optDoubleObject(0, 0.0), "unexpected optDoubleObject value"); + assertEquals(0, ja.optBigInteger(0, BigInteger.ZERO).compareTo(new BigInteger("123")), "unexpected optBigInteger value"); + assertEquals(0, ja.optBigDecimal(0, BigDecimal.ZERO).compareTo(new BigDecimal("123")), "unexpected optBigDecimal value"); Util.checkJSONArrayMaps(ja); } @@ -675,7 +620,7 @@ public void optStringConversion(){ */ @SuppressWarnings("boxing") @Test - public void put() { + void put() { JSONArray jsonArray = new JSONArray(); // index 0 @@ -724,25 +669,25 @@ public void put() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 10 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 10); - assertTrue("expected true", Boolean.TRUE.equals(jsonArray.query("/0"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonArray.query("/1"))); - assertTrue("expected 2 items in [2]", ((List)(JsonPath.read(doc, "$[2]"))).size() == 2); - assertTrue("expected hello", "hello".equals(jsonArray.query("/2/0"))); - assertTrue("expected world", "world".equals(jsonArray.query("/2/1"))); - assertTrue("expected 2.5", Double.valueOf(2.5).equals(jsonArray.query("/3"))); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/4"))); - assertTrue("expected 45", Long.valueOf(45).equals(jsonArray.query("/5"))); - assertTrue("expected objectPut", "objectPut".equals(jsonArray.query("/6"))); - assertTrue("expected 3 items in [7]", ((Map)(JsonPath.read(doc, "$[7]"))).size() == 3); - assertTrue("expected val10", "val10".equals(jsonArray.query("/7/key10"))); - assertTrue("expected val20", "val20".equals(jsonArray.query("/7/key20"))); - assertTrue("expected val30", "val30".equals(jsonArray.query("/7/key30"))); - assertTrue("expected 1 item in [8]", ((Map)(JsonPath.read(doc, "$[8]"))).size() == 1); - assertTrue("expected v1", "v1".equals(jsonArray.query("/8/k1"))); - assertTrue("expected 2 items in [9]", ((List)(JsonPath.read(doc, "$[9]"))).size() == 2); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/9/0"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/9/1"))); + assertEquals(10, ((List)(JsonPath.read(doc, "$"))).size(), "expected 10 top level items"); + assertEquals(Boolean.TRUE, jsonArray.query("/0"), "expected true"); + assertEquals(Boolean.FALSE, jsonArray.query("/1"), "expected false"); + assertEquals(2, ((List)(JsonPath.read(doc, "$[2]"))).size(), "expected 2 items in [2]"); + assertEquals("hello", jsonArray.query("/2/0"), "expected hello"); + assertEquals("world", jsonArray.query("/2/1"), "expected world"); + assertEquals(Double.valueOf(2.5), jsonArray.query("/3"), "expected 2.5"); + assertEquals(Integer.valueOf(1), jsonArray.query("/4"), "expected 1"); + assertEquals(Long.valueOf(45), jsonArray.query("/5"), "expected 45"); + assertEquals("objectPut", jsonArray.query("/6"), "expected objectPut"); + assertEquals(3, ((Map)(JsonPath.read(doc, "$[7]"))).size(), "expected 3 items in [7]"); + assertEquals("val10", jsonArray.query("/7/key10"), "expected val10"); + assertEquals("val20", jsonArray.query("/7/key20"), "expected val20"); + assertEquals("val30", jsonArray.query("/7/key30"), "expected val30"); + assertEquals(1, ((Map)(JsonPath.read(doc, "$[8]"))).size(), "expected 1 item in [8]"); + assertEquals("v1", jsonArray.query("/8/k1"), "expected v1"); + assertEquals(2, ((List)(JsonPath.read(doc, "$[9]"))).size(), "expected 2 items in [9]"); + assertEquals(Integer.valueOf(1), jsonArray.query("/9/0"), "expected 1"); + assertEquals(Integer.valueOf(2), jsonArray.query("/9/1"), "expected 2"); Util.checkJSONArrayMaps(jsonArray); Util.checkJSONObjectMaps(jsonObject); } @@ -753,7 +698,7 @@ public void put() { */ @SuppressWarnings("boxing") @Test - public void putIndex() { + void putIndex() { JSONArray jsonArray = new JSONArray(); // 1 @@ -799,31 +744,31 @@ public void putIndex() { jsonArray.put(10, map); try { jsonArray.put(-1, "abc"); - assertTrue("put index < 0 should have thrown exception", false); + assertTrue(false, "put index < 0 should have thrown exception"); } catch(Exception ignored) {} // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 11 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 11); - assertTrue("expected true", Boolean.TRUE.equals(jsonArray.query("/0"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonArray.query("/1"))); - assertTrue("expected 2 items in [2]", ((List)(JsonPath.read(doc, "$[2]"))).size() == 2); - assertTrue("expected hello", "hello".equals(jsonArray.query("/2/0"))); - assertTrue("expected world", "world".equals(jsonArray.query("/2/1"))); - assertTrue("expected 2.5", Double.valueOf(2.5).equals(jsonArray.query("/3"))); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/4"))); - assertTrue("expected 45", Long.valueOf(45).equals(jsonArray.query("/5"))); - assertTrue("expected objectPut", "objectPut".equals(jsonArray.query("/6"))); - assertTrue("expected null", JSONObject.NULL.equals(jsonArray.query("/7"))); - assertTrue("expected 3 items in [8]", ((Map)(JsonPath.read(doc, "$[8]"))).size() == 3); - assertTrue("expected val10", "val10".equals(jsonArray.query("/8/key10"))); - assertTrue("expected val20", "val20".equals(jsonArray.query("/8/key20"))); - assertTrue("expected val30", "val30".equals(jsonArray.query("/8/key30"))); - assertTrue("expected 2 items in [9]", ((List)(JsonPath.read(doc, "$[9]"))).size() == 2); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/9/0"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/9/1"))); - assertTrue("expected 1 item in [10]", ((Map)(JsonPath.read(doc, "$[10]"))).size() == 1); - assertTrue("expected v1", "v1".equals(jsonArray.query("/10/k1"))); + assertEquals(11, ((List)(JsonPath.read(doc, "$"))).size(), "expected 11 top level items"); + assertEquals(Boolean.TRUE, jsonArray.query("/0"), "expected true"); + assertEquals(Boolean.FALSE, jsonArray.query("/1"), "expected false"); + assertEquals(2, ((List)(JsonPath.read(doc, "$[2]"))).size(), "expected 2 items in [2]"); + assertEquals("hello", jsonArray.query("/2/0"), "expected hello"); + assertEquals("world", jsonArray.query("/2/1"), "expected world"); + assertEquals(Double.valueOf(2.5), jsonArray.query("/3"), "expected 2.5"); + assertEquals(Integer.valueOf(1), jsonArray.query("/4"), "expected 1"); + assertEquals(Long.valueOf(45), jsonArray.query("/5"), "expected 45"); + assertEquals("objectPut", jsonArray.query("/6"), "expected objectPut"); + assertEquals(JSONObject.NULL, jsonArray.query("/7"), "expected null"); + assertEquals(3, ((Map)(JsonPath.read(doc, "$[8]"))).size(), "expected 3 items in [8]"); + assertEquals("val10", jsonArray.query("/8/key10"), "expected val10"); + assertEquals("val20", jsonArray.query("/8/key20"), "expected val20"); + assertEquals("val30", jsonArray.query("/8/key30"), "expected val30"); + assertEquals(2, ((List)(JsonPath.read(doc, "$[9]"))).size(), "expected 2 items in [9]"); + assertEquals(Integer.valueOf(1), jsonArray.query("/9/0"), "expected 1"); + assertEquals(Integer.valueOf(2), jsonArray.query("/9/1"), "expected 2"); + assertEquals(1, ((Map)(JsonPath.read(doc, "$[10]"))).size(), "expected 1 item in [10]"); + assertEquals("v1", jsonArray.query("/10/k1"), "expected v1"); Util.checkJSONObjectMaps(jsonObject); Util.checkJSONArrayMaps(jsonArray); } @@ -833,15 +778,15 @@ public void putIndex() { * and confirm the resulting JSONArray. */ @Test - public void remove() { + void remove() { String arrayStr1 = "["+ "1"+ "]"; JSONArray jsonArray = new JSONArray(arrayStr1); jsonArray.remove(0); - assertTrue("array should be empty", null == jsonArray.remove(5)); - assertTrue("jsonArray should be empty", jsonArray.isEmpty()); + assertTrue(null == jsonArray.remove(5), "array should be empty"); + assertTrue(jsonArray.isEmpty(), "jsonArray should be empty"); Util.checkJSONArrayMaps(jsonArray); } @@ -850,14 +795,14 @@ public void remove() { * and confirm the results when not similar. */ @Test - public void notSimilar() { + void notSimilar() { String arrayStr1 = "["+ "1"+ "]"; JSONArray jsonArray = new JSONArray(arrayStr1); JSONArray otherJsonArray = new JSONArray(); - assertTrue("arrays lengths differ", !jsonArray.similar(otherJsonArray)); + assertFalse(jsonArray.similar(otherJsonArray), "arrays lengths differ"); JSONObject jsonObject = new JSONObject("{\"k1\":\"v1\"}"); JSONObject otherJsonObject = new JSONObject(); @@ -865,7 +810,7 @@ public void notSimilar() { jsonArray.put(jsonObject); otherJsonArray = new JSONArray(); otherJsonArray.put(otherJsonObject); - assertTrue("arrays JSONObjects differ", !jsonArray.similar(otherJsonArray)); + assertFalse(jsonArray.similar(otherJsonArray), "arrays JSONObjects differ"); JSONArray nestedJsonArray = new JSONArray("[1, 2]"); JSONArray otherNestedJsonArray = new JSONArray(); @@ -873,15 +818,13 @@ public void notSimilar() { jsonArray.put(nestedJsonArray); otherJsonArray = new JSONArray(); otherJsonArray.put(otherNestedJsonArray); - assertTrue("arrays nested JSONArrays differ", - !jsonArray.similar(otherJsonArray)); + assertFalse(jsonArray.similar(otherJsonArray), "arrays nested JSONArrays differ"); jsonArray = new JSONArray(); jsonArray.put("hello"); otherJsonArray = new JSONArray(); otherJsonArray.put("world"); - assertTrue("arrays values differ", - !jsonArray.similar(otherJsonArray)); + assertFalse(jsonArray.similar(otherJsonArray), "arrays values differ"); Util.checkJSONArraysMaps(new ArrayList(Arrays.asList( jsonArray, otherJsonArray ))); @@ -894,7 +837,7 @@ public void notSimilar() { * Exercise JSONArray toString() method with various indent levels. */ @Test - public void jsonArrayToStringIndent() { + void jsonArrayToStringIndent() { String jsonArray0Str = "[" + "[1,2," + @@ -954,19 +897,19 @@ public void jsonArrayToStringIndent() { }; JSONArray jsonArray = new JSONArray(jsonArray0Str); String [] actualStrArray = jsonArray.toString().split("\\r?\\n"); - assertEquals("Expected 1 line", 1, actualStrArray.length); + assertEquals(1, actualStrArray.length, "Expected 1 line"); actualStrArray = jsonArray.toString(0).split("\\r?\\n"); - assertEquals("Expected 1 line", 1, actualStrArray.length); + assertEquals(1, actualStrArray.length, "Expected 1 line"); actualStrArray = jsonArray.toString(1).split("\\r?\\n"); - assertEquals("Expected lines", jsonArray1Strs.length, actualStrArray.length); + assertEquals(jsonArray1Strs.length, actualStrArray.length, "Expected lines"); List list = Arrays.asList(actualStrArray); for (String s : jsonArray1Strs) { list.contains(s); } actualStrArray = jsonArray.toString(4).split("\\r?\\n"); - assertEquals("Expected lines", jsonArray1Strs.length, actualStrArray.length); + assertEquals(jsonArray1Strs.length, actualStrArray.length, "Expected lines"); list = Arrays.asList(actualStrArray); for (String s : jsonArray4Strs) { list.contains(s); @@ -978,11 +921,11 @@ public void jsonArrayToStringIndent() { * Convert an empty JSONArray to JSONObject */ @Test - public void toJSONObject() { + void toJSONObject() { JSONArray names = new JSONArray(); JSONArray jsonArray = new JSONArray(); - assertTrue("toJSONObject should return null", - null == jsonArray.toJSONObject(names)); + assertTrue(null == jsonArray.toJSONObject(names), + "toJSONObject should return null"); Util.checkJSONArraysMaps(new ArrayList(Arrays.asList( names, jsonArray ))); @@ -992,21 +935,21 @@ public void toJSONObject() { * Confirm the creation of a JSONArray from an array of ints */ @Test - public void objectArrayVsIsArray() { + void objectArrayVsIsArray() { int[] myInts = { 1, 2, 3, 4, 5, 6, 7 }; Object myObject = myInts; JSONArray jsonArray = new JSONArray(myObject); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 7 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 7); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); - assertTrue("expected 4", Integer.valueOf(4).equals(jsonArray.query("/3"))); - assertTrue("expected 5", Integer.valueOf(5).equals(jsonArray.query("/4"))); - assertTrue("expected 6", Integer.valueOf(6).equals(jsonArray.query("/5"))); - assertTrue("expected 7", Integer.valueOf(7).equals(jsonArray.query("/6"))); + assertEquals(7, ((List)(JsonPath.read(doc, "$"))).size(), "expected 7 top level items"); + assertEquals(Integer.valueOf(1), jsonArray.query("/0"), "expected 1"); + assertEquals(Integer.valueOf(2), jsonArray.query("/1"), "expected 2"); + assertEquals(Integer.valueOf(3), jsonArray.query("/2"), "expected 3"); + assertEquals(Integer.valueOf(4), jsonArray.query("/3"), "expected 4"); + assertEquals(Integer.valueOf(5), jsonArray.query("/4"), "expected 5"); + assertEquals(Integer.valueOf(6), jsonArray.query("/5"), "expected 6"); + assertEquals(Integer.valueOf(7), jsonArray.query("/6"), "expected 7"); Util.checkJSONArrayMaps(jsonArray); } @@ -1015,60 +958,53 @@ public void objectArrayVsIsArray() { */ @SuppressWarnings("boxing") @Test - public void iteratorTest() { + void iteratorTest() { JSONArray jsonArray = new JSONArray(this.arrayStr); Iterator it = jsonArray.iterator(); - assertTrue("Array true", - Boolean.TRUE.equals(it.next())); - assertTrue("Array false", - Boolean.FALSE.equals(it.next())); - assertTrue("Array string true", - "true".equals(it.next())); - assertTrue("Array string false", - "false".equals(it.next())); - assertTrue("Array string", - "hello".equals(it.next())); - - assertTrue("Array double [23.45e-4]", - new BigDecimal("0.002345").equals(it.next())); - assertTrue("Array string double", - Double.valueOf(23.45).equals(Double.parseDouble((String)it.next()))); - - assertTrue("Array value int", - Integer.valueOf(42).equals(it.next())); - assertTrue("Array value string int", - Integer.valueOf(43).equals(Integer.parseInt((String)it.next()))); + assertEquals(Boolean.TRUE, it.next(), "Array true"); + assertEquals(Boolean.FALSE, it.next(), "Array false"); + assertEquals("true", it.next(), "Array string true"); + assertEquals("false", it.next(), "Array string false"); + assertEquals("hello", it.next(), "Array string"); + + assertEquals(new BigDecimal("0.002345"), it.next(), "Array double [23.45e-4]"); + assertEquals(Double.valueOf(23.45), Double.parseDouble((String)it.next()), "Array string double"); + + assertEquals(Integer.valueOf(42), it.next(), "Array value int"); + assertEquals(Integer.valueOf(43), Integer.parseInt((String)it.next()), "Array value string int"); JSONArray nestedJsonArray = (JSONArray)it.next(); - assertTrue("Array value JSONArray", nestedJsonArray != null); + assertTrue(nestedJsonArray != null, "Array value JSONArray"); JSONObject nestedJsonObject = (JSONObject)it.next(); - assertTrue("Array value JSONObject", nestedJsonObject != null); + assertTrue(nestedJsonObject != null, "Array value JSONObject"); - assertTrue("Array value long", - Long.valueOf(0).equals(((Number) it.next()).longValue())); - assertTrue("Array value string long", - Long.valueOf(-1).equals(Long.parseLong((String) it.next()))); - assertTrue("should be at end of array", !it.hasNext()); + assertEquals(Long.valueOf(0), ((Number)it.next()).longValue(), "Array value long"); + assertEquals(Long.valueOf(-1), Long.parseLong((String)it.next()), "Array value string long"); + assertFalse(it.hasNext(), "should be at end of array"); Util.checkJSONArraysMaps(new ArrayList(Arrays.asList( jsonArray, nestedJsonArray ))); Util.checkJSONObjectMaps(nestedJsonObject); } - - @Test(expected = JSONPointerException.class) - public void queryWithNoResult() { - new JSONArray().query("/a/b"); + + @Test + void queryWithNoResult() { + assertThrows(JSONPointerException.class, () -> { + new JSONArray().query("/a/b"); + }); } - + @Test - public void optQueryWithNoResult() { + void optQueryWithNoResult() { assertNull(new JSONArray().optQuery("/a/b")); } - - @Test(expected = IllegalArgumentException.class) - public void optQueryWithSyntaxError() { - new JSONArray().optQuery("invalid"); + + @Test + void optQueryWithSyntaxError() { + assertThrows(IllegalArgumentException.class, () -> { + new JSONArray().optQuery("invalid"); + }); } @@ -1076,7 +1012,7 @@ public void optQueryWithSyntaxError() { * Exercise the JSONArray write() method */ @Test - public void write() throws IOException { + void write() throws IOException { String str = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":2,\"key3\":3}]"; JSONArray jsonArray = new JSONArray(str); String expectedStr = str; @@ -1086,12 +1022,12 @@ public void write() throws IOException { String actualStr = stringWriter.toString(); JSONArray finalArray = new JSONArray(actualStr); Util.compareActualVsExpectedJsonArrays(jsonArray, finalArray); - assertTrue("write() expected " + expectedStr + - " but found " + actualStr, - actualStr.startsWith("[\"value1\",\"value2\",{") + assertTrue(actualStr.startsWith("[\"value1\",\"value2\",{") && actualStr.contains("\"key1\":1") && actualStr.contains("\"key2\":2") - && actualStr.contains("\"key3\":3") + && actualStr.contains("\"key3\":3"), + "write() expected " + expectedStr + + " but found " + actualStr ); } finally { stringWriter.close(); @@ -1121,7 +1057,7 @@ public void writeAppendable() { * Exercise the JSONArray write(Writer, int, int) method */ @Test - public void write3Param() throws IOException { + void write3Param() throws IOException { String str0 = "[\"value1\",\"value2\",{\"key1\":1,\"key2\":false,\"key3\":3.14}]"; JSONArray jsonArray = new JSONArray(str0); String expectedStr = str0; @@ -1130,12 +1066,12 @@ public void write3Param() throws IOException { String actualStr = jsonArray.write(stringWriter, 0, 0).toString(); JSONArray finalArray = new JSONArray(actualStr); Util.compareActualVsExpectedJsonArrays(jsonArray, finalArray); - assertTrue("write() expected " + expectedStr + - " but found " + actualStr, - actualStr.startsWith("[\"value1\",\"value2\",{") + assertTrue(actualStr.startsWith("[\"value1\",\"value2\",{") && actualStr.contains("\"key1\":1") && actualStr.contains("\"key2\":false") - && actualStr.contains("\"key3\":3.14") + && actualStr.contains("\"key3\":3.14"), + "write() expected " + expectedStr + + " but found " + actualStr ); } finally { stringWriter.close(); @@ -1146,15 +1082,15 @@ public void write3Param() throws IOException { String actualStr = jsonArray.write(stringWriter, 2, 1).toString(); JSONArray finalArray = new JSONArray(actualStr); Util.compareActualVsExpectedJsonArrays(jsonArray, finalArray); - assertTrue("write() expected " + expectedStr + - " but found " + actualStr, - actualStr.startsWith("[\n" + + assertTrue(actualStr.startsWith("[\n" + " \"value1\",\n" + " \"value2\",\n" + " {") && actualStr.contains("\"key1\": 1") && actualStr.contains("\"key2\": false") - && actualStr.contains("\"key3\": 3.14") + && actualStr.contains("\"key3\": 3.14"), + "write() expected " + expectedStr + + " but found " + actualStr ); Util.checkJSONArrayMaps(finalArray); } finally { @@ -1199,7 +1135,7 @@ public void write3ParamAppendable() { * Exercise JSONArray toString() method with various indent levels. */ @Test - public void toList() { + void toList() { String jsonArrayStr = "[" + "[1,2," + @@ -1219,58 +1155,58 @@ public void toList() { JSONArray jsonArray = new JSONArray(jsonArrayStr); List list = jsonArray.toList(); - assertTrue("List should not be null", list != null); - assertTrue("List should have 3 elements", list.size() == 3); + assertTrue(list != null, "List should not be null"); + assertEquals(3, list.size(), "List should have 3 elements"); List val1List = (List) list.get(0); - assertTrue("val1 should not be null", val1List != null); - assertTrue("val1 should have 3 elements", val1List.size() == 3); + assertTrue(val1List != null, "val1 should not be null"); + assertEquals(3, val1List.size(), "val1 should have 3 elements"); - assertTrue("val1 value 1 should be 1", val1List.get(0).equals(Integer.valueOf(1))); - assertTrue("val1 value 2 should be 2", val1List.get(1).equals(Integer.valueOf(2))); + assertEquals(val1List.get(0), Integer.valueOf(1), "val1 value 1 should be 1"); + assertEquals(val1List.get(1), Integer.valueOf(2), "val1 value 2 should be 2"); Map key1Value3Map = (Map)val1List.get(2); - assertTrue("Map should not be null", key1Value3Map != null); - assertTrue("Map should have 1 element", key1Value3Map.size() == 1); - assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE)); + assertTrue(key1Value3Map != null, "Map should not be null"); + assertEquals(1, key1Value3Map.size(), "Map should have 1 element"); + assertEquals(Boolean.TRUE, key1Value3Map.get("key3"), "Map key3 should be true"); Map val2Map = (Map) list.get(1); - assertTrue("val2 should not be null", val2Map != null); - assertTrue("val2 should have 4 elements", val2Map.size() == 4); - assertTrue("val2 map key 1 should be val1", val2Map.get("key1").equals("val1")); - assertTrue("val2 map key 3 should be 42", val2Map.get("key3").equals(Integer.valueOf(42))); + assertTrue(val2Map != null, "val2 should not be null"); + assertEquals(4, val2Map.size(), "val2 should have 4 elements"); + assertEquals("val1", val2Map.get("key1"), "val2 map key 1 should be val1"); + assertEquals(val2Map.get("key3"), Integer.valueOf(42), "val2 map key 3 should be 42"); Map val2Key2Map = (Map)val2Map.get("key2"); - assertTrue("val2 map key 2 should not be null", val2Key2Map != null); - assertTrue("val2 map key 2 should have an entry", val2Key2Map.containsKey("key2")); - assertTrue("val2 map key 2 value should be null", val2Key2Map.get("key2") == null); + assertTrue(val2Key2Map != null, "val2 map key 2 should not be null"); + assertTrue(val2Key2Map.containsKey("key2"), "val2 map key 2 should have an entry"); + assertTrue(val2Key2Map.get("key2") == null, "val2 map key 2 value should be null"); List val2Key4List = (List)val2Map.get("key4"); - assertTrue("val2 map key 4 should not be null", val2Key4List != null); - assertTrue("val2 map key 4 should be empty", val2Key4List.isEmpty()); + assertTrue(val2Key4List != null, "val2 map key 4 should not be null"); + assertTrue(val2Key4List.isEmpty(), "val2 map key 4 should be empty"); List val3List = (List) list.get(2); - assertTrue("val3 should not be null", val3List != null); - assertTrue("val3 should have 2 elements", val3List.size() == 2); + assertTrue(val3List != null, "val3 should not be null"); + assertEquals(2, val3List.size(), "val3 should have 2 elements"); List val3Val1List = (List)val3List.get(0); - assertTrue("val3 list val 1 should not be null", val3Val1List != null); - assertTrue("val3 list val 1 should have 2 elements", val3Val1List.size() == 2); - assertTrue("val3 list val 1 list element 1 should be value1", val3Val1List.get(0).equals("value1")); - assertTrue("val3 list val 1 list element 2 should be 2.1", val3Val1List.get(1).equals(new BigDecimal("2.1"))); + assertTrue(val3Val1List != null, "val3 list val 1 should not be null"); + assertEquals(2, val3Val1List.size(), "val3 list val 1 should have 2 elements"); + assertEquals("value1", val3Val1List.get(0), "val3 list val 1 list element 1 should be value1"); + assertEquals(val3Val1List.get(1), new BigDecimal("2.1"), "val3 list val 1 list element 2 should be 2.1"); List val3Val2List = (List)val3List.get(1); - assertTrue("val3 list val 2 should not be null", val3Val2List != null); - assertTrue("val3 list val 2 should have 1 element", val3Val2List.size() == 1); - assertTrue("val3 list val 2 list element 1 should be null", val3Val2List.get(0) == null); + assertTrue(val3Val2List != null, "val3 list val 2 should not be null"); + assertEquals(1, val3Val2List.size(), "val3 list val 2 should have 1 element"); + assertTrue(val3Val2List.get(0) == null, "val3 list val 2 list element 1 should be null"); // assert that toList() is a deep copy jsonArray.getJSONObject(1).put("key1", "still val1"); - assertTrue("val2 map key 1 should be val1", val2Map.get("key1").equals("val1")); + assertEquals("val1", val2Map.get("key1"), "val2 map key 1 should be val1"); // assert that the new list is mutable - assertTrue("Removing an entry should succeed", list.remove(2) != null); - assertTrue("List should have 2 elements", list.size() == 2); + assertTrue(list.remove(2) != null, "Removing an entry should succeed"); + assertEquals(2, list.size(), "List should have 2 elements"); Util.checkJSONArrayMaps(jsonArray); } @@ -1279,32 +1215,32 @@ public void toList() { * Expects an exception if the initial capacity is specified as a negative integer */ @Test - public void testJSONArrayInt() { + void jSONArrayInt() { assertNotNull(new JSONArray(0)); assertNotNull(new JSONArray(5)); // Check Size -> Even though the capacity of the JSONArray can be specified using a positive // integer but the length of JSONArray always reflects upon the items added into it. // assertEquals(0l, new JSONArray(10).length()); try { - assertNotNull("Should throw an exception", new JSONArray(-1)); + assertNotNull(new JSONArray(-1), "Should throw an exception"); } catch (JSONException e) { - assertEquals("Expected an exception message", - "JSONArray initial capacity cannot be negative.", - e.getMessage()); + assertEquals("JSONArray initial capacity cannot be negative.", + e.getMessage(), + "Expected an exception message"); } } - + /** * Verifies that the object constructor can properly handle any supported collection object. */ @Test - @SuppressWarnings({ "unchecked", "boxing" }) - public void testObjectConstructor() { + @SuppressWarnings({"unchecked", "boxing"}) + void objectConstructor() { // should copy the array Object o = new Object[] {2, "test2", true}; JSONArray a = new JSONArray(o); - assertNotNull("Should not error", a); - assertEquals("length", 3, a.length()); + assertNotNull(a, "Should not error"); + assertEquals(3, a.length(), "length"); // should NOT copy the collection // this is required for backwards compatibility @@ -1314,7 +1250,7 @@ public void testObjectConstructor() { ((Collection)o).add(false); try { JSONArray a0 = new JSONArray(o); - assertNull("Should error", a0); + assertNull(a0, "Should error"); } catch (JSONException ex) { } @@ -1323,45 +1259,45 @@ public void testObjectConstructor() { o = a; try { JSONArray a1 = new JSONArray(o); - assertNull("Should error", a1); + assertNull(a1, "Should error"); } catch (JSONException ex) { } Util.checkJSONArrayMaps(a); } - + /** * Verifies that the JSONArray constructor properly copies the original. */ @Test - public void testJSONArrayConstructor() { + void jSONArrayConstructor() { // should copy the array JSONArray a1 = new JSONArray("[2, \"test2\", true]"); JSONArray a2 = new JSONArray(a1); - assertNotNull("Should not error", a2); - assertEquals("length", a1.length(), a2.length()); + assertNotNull(a2, "Should not error"); + assertEquals(a1.length(), a2.length(), "length"); for(int i = 0; i < a1.length(); i++) { - assertEquals("index " + i + " are equal", a1.get(i), a2.get(i)); + assertEquals(a1.get(i), a2.get(i), "index " + i + " are equal"); } Util.checkJSONArraysMaps(new ArrayList(Arrays.asList( a1, a2 ))); } - + /** * Verifies that the object constructor can properly handle any supported collection object. */ @Test - public void testJSONArrayPutAll() { + void jSONArrayPutAll() { // should copy the array JSONArray a1 = new JSONArray("[2, \"test2\", true]"); JSONArray a2 = new JSONArray(); a2.putAll(a1); - assertNotNull("Should not error", a2); - assertEquals("length", a1.length(), a2.length()); + assertNotNull(a2, "Should not error"); + assertEquals(a1.length(), a2.length(), "length"); for(int i = 0; i < a1.length(); i++) { - assertEquals("index " + i + " are equal", a1.get(i), a2.get(i)); + assertEquals(a1.get(i), a2.get(i), "index " + i + " are equal"); } Util.checkJSONArraysMaps(new ArrayList(Arrays.asList( a1, a2 @@ -1369,38 +1305,42 @@ public void testJSONArrayPutAll() { } /** - * Tests if calling JSONArray clear() method actually makes the JSONArray empty - */ - @Test(expected = JSONException.class) - public void jsonArrayClearMethodTest() { - //Adds random stuff to the JSONArray - JSONArray jsonArray = new JSONArray(); - jsonArray.put(123); - jsonArray.put("456"); - jsonArray.put(new JSONArray()); - jsonArray.clear(); //Clears the JSONArray - assertTrue("expected jsonArray.length() == 0", jsonArray.length() == 0); //Check if its length is 0 - jsonArray.getInt(0); //Should throws org.json.JSONException: JSONArray[0] not found - Util.checkJSONArrayMaps(jsonArray); - } + * Tests if calling JSONArray clear() method actually makes the JSONArray empty + */ + @Test + void jsonArrayClearMethodTest() { + assertThrows(JSONException.class, () -> { + //Adds random stuff to the JSONArray + JSONArray jsonArray = new JSONArray(); + jsonArray.put(123); + jsonArray.put("456"); + jsonArray.put(new JSONArray()); + jsonArray.clear(); //Clears the JSONArray + assertEquals(0, jsonArray.length(), "expected jsonArray.length() == 0"); //Check if its length is 0 + jsonArray.getInt(0); //Should throws org.json.JSONException: JSONArray[0] not found + Util.checkJSONArrayMaps(jsonArray); + }); + } /** * Tests for stack overflow. See https://github.com/stleary/JSON-java/issues/654 */ - @Ignore("This test relies on system constraints and may not always pass. See: https://github.com/stleary/JSON-java/issues/821") - @Test(expected = JSONException.class) - public void issue654StackOverflowInputWellFormed() { - //String input = new String(java.util.Base64.getDecoder().decode(base64Bytes)); - final InputStream resourceAsStream = JSONArrayTest.class.getClassLoader().getResourceAsStream("Issue654WellFormedArray.json"); - JSONTokener tokener = new JSONTokener(resourceAsStream); - JSONArray json_input = new JSONArray(tokener); - assertNotNull(json_input); - fail("Excepected Exception due to stack overflow."); - Util.checkJSONArrayMaps(json_input); + @Disabled("This test relies on system constraints and may not always pass. See: https://github.com/stleary/JSON-java/issues/821") + @Test + void issue654StackOverflowInputWellFormed() { + assertThrows(JSONException.class, () -> { + //String input = new String(java.util.Base64.getDecoder().decode(base64Bytes)); + final InputStream resourceAsStream = JSONArrayTest.class.getClassLoader().getResourceAsStream("Issue654WellFormedArray.json"); + JSONTokener tokener = new JSONTokener(resourceAsStream); + JSONArray json_input = new JSONArray(tokener); + assertNotNull(json_input); + fail("Excepected Exception due to stack overflow."); + Util.checkJSONArrayMaps(json_input); + }); } @Test - public void testIssue682SimilarityOfJSONString() { + void issue682SimilarityOfJSONString() { JSONArray ja1 = new JSONArray() .put(new MyJsonString()) .put(2); @@ -1420,69 +1360,81 @@ public String toJSONString() { assertFalse(ja1.similar(ja3)); } - @Test(expected = JSONException.class) - public void testRecursiveDepth() { - HashMap map = new HashMap<>(); - map.put("t", map); - new JSONArray().put(map); + @Test + void recursiveDepth() { + assertThrows(JSONException.class, () -> { + HashMap map = new HashMap<>(); + map.put("t", map); + new JSONArray().put(map); + }); } - @Test(expected = JSONException.class) - public void testRecursiveDepthAtPosition() { - HashMap map = new HashMap<>(); - map.put("t", map); - new JSONArray().put(0, map); + @Test + void recursiveDepthAtPosition() { + assertThrows(JSONException.class, () -> { + HashMap map = new HashMap<>(); + map.put("t", map); + new JSONArray().put(0, map); + }); } - @Test(expected = JSONException.class) - public void testRecursiveDepthArray() { - ArrayList array = new ArrayList<>(); - array.add(array); - new JSONArray(array); + @Test + void recursiveDepthArray() { + assertThrows(JSONException.class, () -> { + ArrayList array = new ArrayList<>(); + array.add(array); + new JSONArray(array); + }); } @Test - public void testRecursiveDepthAtPositionDefaultObject() { + void recursiveDepthAtPositionDefaultObject() { HashMap map = JSONObjectTest.buildNestedMap(ParserConfiguration.DEFAULT_MAXIMUM_NESTING_DEPTH); new JSONArray().put(0, map); } @Test - public void testRecursiveDepthAtPosition1000Object() { + void recursiveDepthAtPosition1000Object() { HashMap map = JSONObjectTest.buildNestedMap(1000); new JSONArray().put(0, map, new JSONParserConfiguration().withMaxNestingDepth(1000)); } - @Test(expected = JSONException.class) - public void testRecursiveDepthAtPosition1001Object() { - HashMap map = JSONObjectTest.buildNestedMap(1001); - new JSONArray().put(0, map); + @Test + void recursiveDepthAtPosition1001Object() { + assertThrows(JSONException.class, () -> { + HashMap map = JSONObjectTest.buildNestedMap(1001); + new JSONArray().put(0, map); + }); } - @Test(expected = JSONException.class) - public void testRecursiveDepthArrayLimitedMaps() { - ArrayList array = new ArrayList<>(); - array.add(array); - new JSONArray(array); + @Test + void recursiveDepthArrayLimitedMaps() { + assertThrows(JSONException.class, () -> { + ArrayList array = new ArrayList<>(); + array.add(array); + new JSONArray(array); + }); } @Test - public void testRecursiveDepthArrayForDefaultLevels() { + void recursiveDepthArrayForDefaultLevels() { ArrayList array = buildNestedArray(ParserConfiguration.DEFAULT_MAXIMUM_NESTING_DEPTH); new JSONArray(array, new JSONParserConfiguration()); } @Test - public void testRecursiveDepthArrayFor1000Levels() { + void recursiveDepthArrayFor1000Levels() { ArrayList array = buildNestedArray(1000); JSONParserConfiguration parserConfiguration = new JSONParserConfiguration().withMaxNestingDepth(1000); new JSONArray(array, parserConfiguration); } - @Test(expected = JSONException.class) - public void testRecursiveDepthArrayFor1001Levels() { - ArrayList array = buildNestedArray(1001); - new JSONArray(array); + @Test + void recursiveDepthArrayFor1001Levels() { + assertThrows(JSONException.class, () -> { + ArrayList array = buildNestedArray(1001); + new JSONArray(array); + }); } public static ArrayList buildNestedArray(int maxDepth) { diff --git a/src/test/java/org/json/junit/JSONMLTest.java b/src/test/java/org/json/junit/JSONMLTest.java index e6abd151e..81887c53f 100644 --- a/src/test/java/org/json/junit/JSONMLTest.java +++ b/src/test/java/org/json/junit/JSONMLTest.java @@ -4,10 +4,11 @@ Public Domain. */ -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import org.json.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; /** * Tests for org.json.JSONML.java @@ -25,16 +26,18 @@ * Convert a string -> JSONObject -> string -> JSONArray -> string * */ -public class JSONMLTest { +class JSONMLTest { /** * Attempts to transform a null XML string to JSON. * Expects a NullPointerException */ - @Test(expected=NullPointerException.class) - public void nullXMLException() { - String xmlStr = null; - JSONML.toJSONArray(xmlStr); + @Test + void nullXMLException() { + assertThrows(NullPointerException.class, () -> { + String xmlStr = null; + JSONML.toJSONArray(xmlStr); + }); } /** @@ -42,15 +45,15 @@ public void nullXMLException() { * Expects a JSONException */ @Test - public void emptyXMLException() { + void emptyXMLException() { String xmlStr = ""; try { JSONML.toJSONArray(xmlStr); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Bad XML at 0 [character 1 line 1]", - e.getMessage()); + assertEquals("Bad XML at 0 [character 1 line 1]", + e.getMessage(), + "Expecting an exception message"); } } @@ -58,13 +61,15 @@ public void emptyXMLException() { * Attempts to call JSONML.toString() with a null JSONArray. * Expects a NullPointerException. */ - @Test(expected=NullPointerException.class) - public void nullJSONXMLException() { - /** - * Tries to convert a null JSONArray to XML. - */ - JSONArray jsonArray= null; - JSONML.toString(jsonArray); + @Test + void nullJSONXMLException() { + assertThrows(NullPointerException.class, () -> { + /** + * Tries to convert a null JSONArray to XML. + */ + JSONArray jsonArray = null; + JSONML.toString(jsonArray); + }); } /** @@ -72,18 +77,16 @@ public void nullJSONXMLException() { * Expects a JSONException. */ @Test - public void emptyJSONXMLException() { + void emptyJSONXMLException() { /** * Tries to convert an empty JSONArray to XML. */ JSONArray jsonArray = new JSONArray(); try { JSONML.toString(jsonArray); - assertTrue("Expecting an exception", false); + assertTrue(false, "Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "JSONArray[0] not found.". - equals(e.getMessage())); + assertEquals("JSONArray[0] not found.", e.getMessage(), "Expecting an exception message"); } } @@ -92,7 +95,7 @@ public void emptyJSONXMLException() { * Expects a JSONException */ @Test - public void nonXMLException() { + void nonXMLException() { /** * Attempts to transform a nonXML string to JSON */ @@ -101,9 +104,9 @@ public void nonXMLException() { JSONML.toJSONArray(xmlStr); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Bad XML at 23 [character 24 line 1]", - e.getMessage()); + assertEquals("Bad XML at 23 [character 24 line 1]", + e.getMessage(), + "Expecting an exception message"); } } @@ -114,7 +117,7 @@ public void nonXMLException() { * Expects a JSONException */ @Test - public void emptyTagException() { + void emptyTagException() { /** * jsonArrayStr is used to build a JSONArray which is then * turned into XML. For this transformation, all arrays represent @@ -135,11 +138,11 @@ public void emptyTagException() { JSONArray jsonArray = new JSONArray(jsonArrayStr); try { JSONML.toString(jsonArray); - assertTrue("Expecting an exception", false); + assertTrue(false, "Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONArray[0] is not a String (class org.json.JSONArray).", - e.getMessage()); + assertEquals("JSONArray[0] is not a String (class org.json.JSONArray).", + e.getMessage(), + "Expecting an exception message"); } } @@ -149,7 +152,7 @@ public void emptyTagException() { * to a JSONArray then back to string. Expects a JSONException */ @Test - public void spaceInTagException() { + void spaceInTagException() { /** * jsonArrayStr is used to build a JSONArray which is then * turned into XML. For this transformation, all arrays represent @@ -171,11 +174,9 @@ public void spaceInTagException() { JSONArray jsonArray = new JSONArray(jsonArrayStr); try { JSONML.toString(jsonArray); - assertTrue("Expecting an exception", false); + assertTrue(false, "Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "'addr esses' contains a space character.". - equals(e.getMessage())); + assertEquals("'addr esses' contains a space character.", e.getMessage(), "Expecting an exception message"); } } @@ -185,7 +186,7 @@ public void spaceInTagException() { * Expects a JSONException */ @Test - public void invalidSlashInTagException() { + void invalidSlashInTagException() { /** * xmlStr contains XML text which is transformed into a JSONArray. * In this case, the XML is invalid because the 'name' element @@ -204,9 +205,9 @@ public void invalidSlashInTagException() { JSONML.toJSONArray(xmlStr); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Misshaped tag at 176 [character 14 line 4]", - e.getMessage()); + assertEquals("Misshaped tag at 176 [character 14 line 4]", + e.getMessage(), + "Expecting an exception message"); } } @@ -215,7 +216,7 @@ public void invalidSlashInTagException() { * Expects a JSONException. */ @Test - public void invalidBangInTagException() { + void invalidBangInTagException() { String xmlStr = "\n"+ ""; try { JSONML.toJSONArray(xmlStr); - assertTrue("Expecting an exception", false); + assertTrue(false, "Expecting an exception"); } catch (JSONException e) { - assertTrue("Expecting an exception message", - "Expected a closing name instead of '>'.". - equals(e.getMessage())); + assertEquals("Expected a closing name instead of '>'.", e.getMessage(), "Expecting an exception message"); } } @@ -330,7 +329,7 @@ public void noCloseEndTagException() { * into a JSONArray. Expects a JSONException. */ @Test - public void noCloseEndBraceException() { + void noCloseEndBraceException() { /** * xmlStr contains XML text which is transformed into a JSONArray. * In this case, the XML is invalid because an element @@ -349,9 +348,9 @@ public void noCloseEndBraceException() { JSONML.toJSONArray(xmlStr); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Misplaced '<' at 206 [character 1 line 7]", - e.getMessage()); + assertEquals("Misplaced '<' at 206 [character 1 line 7]", + e.getMessage(), + "Expecting an exception message"); } } @@ -360,7 +359,7 @@ public void noCloseEndBraceException() { * into a JSONArray. Expects a JSONException. */ @Test - public void invalidCDATABangInTagException() { + void invalidCDATABangInTagException() { /** * xmlStr contains XML text which is transformed into a JSONArray. * In this case, the XML is invalid because an element @@ -379,9 +378,9 @@ public void invalidCDATABangInTagException() { JSONML.toJSONArray(xmlStr); fail("Expecting an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Expected 'CDATA[' at 204 [character 11 line 5]", - e.getMessage()); + assertEquals("Expected 'CDATA[' at 204 [character 11 line 5]", + e.getMessage(), + "Expecting an exception message"); } } @@ -392,7 +391,7 @@ public void invalidCDATABangInTagException() { * confirm the contents. */ @Test - public void toJSONArray() { + void toJSONArray() { /** * xmlStr contains XML text which is transformed into a JSONArray. * Each element becomes a JSONArray: @@ -448,7 +447,7 @@ public void toJSONArray() { * transformations work. */ @Test - public void toJSONObjectToJSONArray() { + void toJSONObjectToJSONArray() { /** * xmlStr contains XML text which is transformed into a JSONObject, * restored to XML, transformed into a JSONArray, and then restored @@ -673,7 +672,7 @@ public void toJSONObjectToJSONArray() { * This test shows how XML comments are handled. */ @Test - public void commentsInXML() { + void commentsInXML() { String xmlStr = "\n"+ @@ -707,7 +706,7 @@ public void commentsInXML() { * result in comment below. */ @Test - public void testToJSONArray_jsonOutput() { + void toJSONArray_jsonOutput() { final String originalXml = "011000True"; final String expectedJsonString = "[\"root\",[\"id\",1],[\"id\",1],[\"id\",0],[\"id\",0],[\"item\",{\"id\":1}],[\"title\",true]]"; final JSONArray actualJsonOutput = JSONML.toJSONArray(originalXml, false); @@ -718,7 +717,7 @@ public void testToJSONArray_jsonOutput() { * JSON string cannot be reverted to original xml when type guessing is used. */ @Test - public void testToJSONArray_reversibility() { + void toJSONArray_reversibility() { final String originalXml = "011000True"; final String revertedXml = JSONML.toString(JSONML.toJSONArray(originalXml, false)); assertNotEquals(revertedXml, originalXml); @@ -729,7 +728,7 @@ public void testToJSONArray_reversibility() { * When we force all the values as string, the original text comes back. */ @Test - public void testToJSONArray_reversibility2() { + void toJSONArray_reversibility2() { final String originalXml = "011000True"; final String expectedJsonString = "[\"root\",[\"id\",\"01\"],[\"id\",\"1\"],[\"id\",\"00\"],[\"id\",\"0\"],[\"item\",{\"id\":\"01\"}],[\"title\",\"True\"]]"; final JSONArray json = JSONML.toJSONArray(originalXml,true); @@ -743,7 +742,7 @@ public void testToJSONArray_reversibility2() { * JSON can be reverted to original xml. */ @Test - public void testToJSONArray_reversibility3() { + void toJSONArray_reversibility3() { final String originalXml = "400402"; final JSONArray jsonArray = JSONML.toJSONArray(originalXml, false); final String revertedXml = JSONML.toString(jsonArray); @@ -755,15 +754,15 @@ public void testToJSONArray_reversibility3() { * comment below. */ @Test - public void testToJSONObject_reversibility() { + void toJSONObject_reversibility() { final String originalXml = "400402"; final JSONObject originalObject=JSONML.toJSONObject(originalXml,false); final String originalJson = originalObject.toString(); final String xml = JSONML.toString(originalObject); final JSONObject revertedObject = JSONML.toJSONObject(xml, false); final String newJson = revertedObject.toString(); - assertTrue("JSON Objects are not similar", originalObject.similar(revertedObject)); - assertTrue("JSON Strings are not similar", new JSONObject(originalJson).similar(new JSONObject(newJson))); + assertTrue(originalObject.similar(revertedObject), "JSON Objects are not similar"); + assertTrue(new JSONObject(originalJson).similar(new JSONObject(newJson)), "JSON Strings are not similar"); } // these tests do not pass for the following reasons: @@ -808,34 +807,36 @@ public void testToJSONObject_reversibility() { // assertEquals(expectedJsonString, actualJsonString); // } - @Test (timeout = 6000) - public void testIssue484InfinteLoop1() { + @Test + @Timeout(6000) + void issue484InfinteLoop1() { try { JSONML.toJSONObject("??*^M??|?CglR^F??`??>?w??PIlr^E??D^X^]?$?-^R?o??O?*??{OD?^FY??`2a????NM?b^Tq?:O?>S$^K?J?^FB.gUK?m^H??zE??^??!v]?^A???^[^A??^U?c??????h???s???g^Z???`?q^Dbi??:^QZl?)?}1^??k?0??:$V?$?Ovs(}J??^V????2;^QgQ?^_^A?^D?^U?Tg?K?`?h%c?hmGA??w??PIlr??D?$?-?o??O?*??{OD?Y??`2a????NM?bq?:O?>S$ ?J?B.gUK?m\b??zE???!v]???????c??????h???s???g???`?qbi??:Zl?)?}1^??k?0??:$V?$?Ovs(}J??????2;gQ????Tg?K?`?h%c?hmGA?"); final int maxNestingDepth = 42; @@ -845,14 +846,14 @@ public void testToJSONArrayMaxNestingDepthOf42IsRespected() { fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Wrong throwable thrown: not expecting message <" + e.getMessage() + ">", - e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth)); + assertTrue(e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth), + "Wrong throwable thrown: not expecting message <" + e.getMessage() + ">"); } } @Test - public void testToJSONArrayMaxNestingDepthIsRespectedWithValidXML() { + void toJSONArrayMaxNestingDepthIsRespectedWithValidXML() { final String perfectlyFineXML = "\n" + " \n" + " sonoo\n" + @@ -868,13 +869,13 @@ public void testToJSONArrayMaxNestingDepthIsRespectedWithValidXML() { fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Wrong throwable thrown: not expecting message <" + e.getMessage() + ">", - e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth)); + assertTrue(e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth), + "Wrong throwable thrown: not expecting message <" + e.getMessage() + ">"); } } @Test - public void testToJSONArrayMaxNestingDepthWithValidFittingXML() { + void toJSONArrayMaxNestingDepthWithValidFittingXML() { final String perfectlyFineXML = "\n" + " \n" + " sonoo\n" + @@ -896,7 +897,7 @@ public void testToJSONArrayMaxNestingDepthWithValidFittingXML() { @Test - public void testToJSONObjectMaxDefaultNestingDepthIsRespected() { + void toJSONObjectMaxDefaultNestingDepthIsRespected() { final String wayTooLongMalformedXML = new String(new char[6000]).replace("\0", ""); try { @@ -904,13 +905,13 @@ public void testToJSONObjectMaxDefaultNestingDepthIsRespected() { fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Wrong throwable thrown: not expecting message <" + e.getMessage() + ">", - e.getMessage().startsWith("Maximum nesting depth of " + JSONMLParserConfiguration.DEFAULT_MAXIMUM_NESTING_DEPTH)); + assertTrue(e.getMessage().startsWith("Maximum nesting depth of " + JSONMLParserConfiguration.DEFAULT_MAXIMUM_NESTING_DEPTH), + "Wrong throwable thrown: not expecting message <" + e.getMessage() + ">"); } } @Test - public void testToJSONObjectUnlimitedNestingDepthIsPossible() { + void toJSONObjectUnlimitedNestingDepthIsPossible() { int actualDepth = JSONMLParserConfiguration.DEFAULT_MAXIMUM_NESTING_DEPTH +10; final String deeperThanDefaultMax = new String(new char[actualDepth]).replace("\0", "") + "value" + @@ -928,7 +929,7 @@ public void testToJSONObjectUnlimitedNestingDepthIsPossible() { @Test - public void testToJSONObjectMaxNestingDepthOf42IsRespected() { + void toJSONObjectMaxNestingDepthOf42IsRespected() { final String wayTooLongMalformedXML = new String(new char[6000]).replace("\0", ""); final int maxNestingDepth = 42; @@ -938,13 +939,13 @@ public void testToJSONObjectMaxNestingDepthOf42IsRespected() { fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Wrong throwable thrown: not expecting message <" + e.getMessage() + ">", - e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth)); + assertTrue(e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth), + "Wrong throwable thrown: not expecting message <" + e.getMessage() + ">"); } } @Test - public void testToJSONObjectMaxNestingDepthIsRespectedWithValidXML() { + void toJSONObjectMaxNestingDepthIsRespectedWithValidXML() { final String perfectlyFineXML = "\n" + " \n" + " sonoo\n" + @@ -960,13 +961,13 @@ public void testToJSONObjectMaxNestingDepthIsRespectedWithValidXML() { fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Wrong throwable thrown: not expecting message <" + e.getMessage() + ">", - e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth)); + assertTrue(e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth), + "Wrong throwable thrown: not expecting message <" + e.getMessage() + ">"); } } @Test - public void testToJSONObjectMaxNestingDepthWithValidFittingXML() { + void toJSONObjectMaxNestingDepthWithValidFittingXML() { final String perfectlyFineXML = "\n" + " \n" + " sonoo\n" + diff --git a/src/test/java/org/json/junit/JSONObjectDecimalTest.java b/src/test/java/org/json/junit/JSONObjectDecimalTest.java index 3302f0a24..a75ca8f28 100644 --- a/src/test/java/org/json/junit/JSONObjectDecimalTest.java +++ b/src/test/java/org/json/junit/JSONObjectDecimalTest.java @@ -1,99 +1,98 @@ package org.json.junit; import org.json.JSONObject; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.math.BigDecimal; -import java.math.BigInteger; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import java.math.BigInteger; -public class JSONObjectDecimalTest { +class JSONObjectDecimalTest { @Test - public void shouldParseDecimalNumberThatStartsWithDecimalPoint(){ + void shouldParseDecimalNumberThatStartsWithDecimalPoint(){ JSONObject jsonObject = new JSONObject("{value:0.50}"); - assertEquals("Float not recognized", 0.5f, jsonObject.getFloat("value"), 0.0f); - assertEquals("Float not recognized", 0.5f, jsonObject.optFloat("value"), 0.0f); - assertEquals("Float not recognized", 0.5f, jsonObject.optFloatObject("value"), 0.0f); - assertEquals("Double not recognized", 0.5d, jsonObject.optDouble("value"), 0.0f); - assertEquals("Double not recognized", 0.5d, jsonObject.optDoubleObject("value"), 0.0f); - assertEquals("Double not recognized", 0.5d, jsonObject.getDouble("value"), 0.0f); - assertEquals("Long not recognized", 0, jsonObject.optLong("value"), 0); - assertEquals("Long not recognized", 0, jsonObject.getLong("value"), 0); - assertEquals("Long not recognized", 0, jsonObject.optLongObject("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.optInt("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.getInt("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.optIntegerObject("value"), 0); - assertEquals("Number not recognized", 0, jsonObject.getNumber("value").intValue(), 0); - assertEquals("Number not recognized", 0, jsonObject.getNumber("value").longValue(), 0); - assertEquals("BigDecimal not recognized", 0, BigDecimal.valueOf(.5).compareTo(jsonObject.getBigDecimal("value"))); - assertEquals("BigInteger not recognized",0, BigInteger.valueOf(0).compareTo(jsonObject.getBigInteger("value"))); + assertEquals(0.5f, jsonObject.getFloat("value"), 0.0f, "Float not recognized"); + assertEquals(0.5f, jsonObject.optFloat("value"), 0.0f, "Float not recognized"); + assertEquals(0.5f, jsonObject.optFloatObject("value"), 0.0f, "Float not recognized"); + assertEquals(0.5d, jsonObject.optDouble("value"), 0.0f, "Double not recognized"); + assertEquals(0.5d, jsonObject.optDoubleObject("value"), 0.0f, "Double not recognized"); + assertEquals(0.5d, jsonObject.getDouble("value"), 0.0f, "Double not recognized"); + assertEquals(0, jsonObject.optLong("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.getLong("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.optLongObject("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.optInt("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.getInt("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.optIntegerObject("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.getNumber("value").intValue(), 0, "Number not recognized"); + assertEquals(0, jsonObject.getNumber("value").longValue(), 0, "Number not recognized"); + assertEquals(0, BigDecimal.valueOf(.5).compareTo(jsonObject.getBigDecimal("value")), "BigDecimal not recognized"); + assertEquals(0, BigInteger.valueOf(0).compareTo(jsonObject.getBigInteger("value")), "BigInteger not recognized"); } - @Test - public void shouldParseNegativeDecimalNumberThatStartsWithDecimalPoint(){ + void shouldParseNegativeDecimalNumberThatStartsWithDecimalPoint(){ JSONObject jsonObject = new JSONObject("{value:-.50}"); - assertEquals("Float not recognized", -0.5f, jsonObject.getFloat("value"), 0.0f); - assertEquals("Float not recognized", -0.5f, jsonObject.optFloat("value"), 0.0f); - assertEquals("Float not recognized", -0.5f, jsonObject.optFloatObject("value"), 0.0f); - assertEquals("Double not recognized", -0.5d, jsonObject.optDouble("value"), 0.0f); - assertEquals("Double not recognized", -0.5d, jsonObject.optDoubleObject("value"), 0.0f); - assertEquals("Double not recognized", -0.5d, jsonObject.getDouble("value"), 0.0f); - assertEquals("Long not recognized", 0, jsonObject.optLong("value"), 0); - assertEquals("Long not recognized", 0, jsonObject.getLong("value"), 0); - assertEquals("Long not recognized", 0, jsonObject.optLongObject("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.optInt("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.getInt("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.optIntegerObject("value"), 0); - assertEquals("Number not recognized", 0, jsonObject.getNumber("value").intValue(), 0); - assertEquals("Number not recognized", 0, jsonObject.getNumber("value").longValue(), 0); - assertEquals("BigDecimal not recognized", 0, BigDecimal.valueOf(-.5).compareTo(jsonObject.getBigDecimal("value"))); - assertEquals("BigInteger not recognized",0, BigInteger.valueOf(0).compareTo(jsonObject.getBigInteger("value"))); + assertEquals(-0.5f, jsonObject.getFloat("value"), 0.0f, "Float not recognized"); + assertEquals(-0.5f, jsonObject.optFloat("value"), 0.0f, "Float not recognized"); + assertEquals(-0.5f, jsonObject.optFloatObject("value"), 0.0f, "Float not recognized"); + assertEquals(-0.5d, jsonObject.optDouble("value"), 0.0f, "Double not recognized"); + assertEquals(-0.5d, jsonObject.optDoubleObject("value"), 0.0f, "Double not recognized"); + assertEquals(-0.5d, jsonObject.getDouble("value"), 0.0f, "Double not recognized"); + assertEquals(0, jsonObject.optLong("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.getLong("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.optLongObject("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.optInt("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.getInt("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.optIntegerObject("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.getNumber("value").intValue(), 0, "Number not recognized"); + assertEquals(0, jsonObject.getNumber("value").longValue(), 0, "Number not recognized"); + assertEquals(0, BigDecimal.valueOf(-.5).compareTo(jsonObject.getBigDecimal("value")), "BigDecimal not recognized"); + assertEquals(0, BigInteger.valueOf(0).compareTo(jsonObject.getBigInteger("value")), "BigInteger not recognized"); } @Test - public void shouldParseDecimalNumberThatHasZeroBeforeWithDecimalPoint(){ + void shouldParseDecimalNumberThatHasZeroBeforeWithDecimalPoint(){ JSONObject jsonObject = new JSONObject("{value:00.050}"); - assertEquals("Float not recognized", 0.05f, jsonObject.getFloat("value"), 0.0f); - assertEquals("Float not recognized", 0.05f, jsonObject.optFloat("value"), 0.0f); - assertEquals("Float not recognized", 0.05f, jsonObject.optFloatObject("value"), 0.0f); - assertEquals("Double not recognized", 0.05d, jsonObject.optDouble("value"), 0.0f); - assertEquals("Double not recognized", 0.05d, jsonObject.optDoubleObject("value"), 0.0f); - assertEquals("Double not recognized", 0.05d, jsonObject.getDouble("value"), 0.0f); - assertEquals("Long not recognized", 0, jsonObject.optLong("value"), 0); - assertEquals("Long not recognized", 0, jsonObject.getLong("value"), 0); - assertEquals("Long not recognized", 0, jsonObject.optLongObject("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.optInt("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.getInt("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.optIntegerObject("value"), 0); - assertEquals("Number not recognized", 0, jsonObject.getNumber("value").intValue(), 0); - assertEquals("Number not recognized", 0, jsonObject.getNumber("value").longValue(), 0); - assertEquals("BigDecimal not recognized", 0, BigDecimal.valueOf(.05).compareTo(jsonObject.getBigDecimal("value"))); - assertEquals("BigInteger not recognized",0, BigInteger.valueOf(0).compareTo(jsonObject.getBigInteger("value"))); + assertEquals(0.05f, jsonObject.getFloat("value"), 0.0f, "Float not recognized"); + assertEquals(0.05f, jsonObject.optFloat("value"), 0.0f, "Float not recognized"); + assertEquals(0.05f, jsonObject.optFloatObject("value"), 0.0f, "Float not recognized"); + assertEquals(0.05d, jsonObject.optDouble("value"), 0.0f, "Double not recognized"); + assertEquals(0.05d, jsonObject.optDoubleObject("value"), 0.0f, "Double not recognized"); + assertEquals(0.05d, jsonObject.getDouble("value"), 0.0f, "Double not recognized"); + assertEquals(0, jsonObject.optLong("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.getLong("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.optLongObject("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.optInt("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.getInt("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.optIntegerObject("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.getNumber("value").intValue(), 0, "Number not recognized"); + assertEquals(0, jsonObject.getNumber("value").longValue(), 0, "Number not recognized"); + assertEquals(0, BigDecimal.valueOf(.05).compareTo(jsonObject.getBigDecimal("value")), "BigDecimal not recognized"); + assertEquals(0, BigInteger.valueOf(0).compareTo(jsonObject.getBigInteger("value")), "BigInteger not recognized"); } @Test - public void shouldParseNegativeDecimalNumberThatHasZeroBeforeWithDecimalPoint(){ + void shouldParseNegativeDecimalNumberThatHasZeroBeforeWithDecimalPoint(){ JSONObject jsonObject = new JSONObject("{value:-00.050}"); - assertEquals("Float not recognized", -0.05f, jsonObject.getFloat("value"), 0.0f); - assertEquals("Float not recognized", -0.05f, jsonObject.optFloat("value"), 0.0f); - assertEquals("Float not recognized", -0.05f, jsonObject.optFloatObject("value"), 0.0f); - assertEquals("Double not recognized", -0.05d, jsonObject.optDouble("value"), 0.0f); - assertEquals("Double not recognized", -0.05d, jsonObject.optDoubleObject("value"), 0.0f); - assertEquals("Double not recognized", -0.05d, jsonObject.getDouble("value"), 0.0f); - assertEquals("Long not recognized", 0, jsonObject.optLong("value"), 0); - assertEquals("Long not recognized", 0, jsonObject.getLong("value"), 0); - assertEquals("Long not recognized", 0, jsonObject.optLongObject("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.optInt("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.getInt("value"), 0); - assertEquals("Integer not recognized", 0, jsonObject.optIntegerObject("value"), 0); - assertEquals("Number not recognized", 0, jsonObject.getNumber("value").intValue(), 0); - assertEquals("Number not recognized", 0, jsonObject.getNumber("value").longValue(), 0); - assertEquals("BigDecimal not recognized", 0, BigDecimal.valueOf(-.05).compareTo(jsonObject.getBigDecimal("value"))); - assertEquals("BigInteger not recognized",0, BigInteger.valueOf(0).compareTo(jsonObject.getBigInteger("value"))); + assertEquals(-0.05f, jsonObject.getFloat("value"), 0.0f, "Float not recognized"); + assertEquals(-0.05f, jsonObject.optFloat("value"), 0.0f, "Float not recognized"); + assertEquals(-0.05f, jsonObject.optFloatObject("value"), 0.0f, "Float not recognized"); + assertEquals(-0.05d, jsonObject.optDouble("value"), 0.0f, "Double not recognized"); + assertEquals(-0.05d, jsonObject.optDoubleObject("value"), 0.0f, "Double not recognized"); + assertEquals(-0.05d, jsonObject.getDouble("value"), 0.0f, "Double not recognized"); + assertEquals(0, jsonObject.optLong("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.getLong("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.optLongObject("value"), 0, "Long not recognized"); + assertEquals(0, jsonObject.optInt("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.getInt("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.optIntegerObject("value"), 0, "Integer not recognized"); + assertEquals(0, jsonObject.getNumber("value").intValue(), 0, "Number not recognized"); + assertEquals(0, jsonObject.getNumber("value").longValue(), 0, "Number not recognized"); + assertEquals(0, BigDecimal.valueOf(-.05).compareTo(jsonObject.getBigDecimal("value")), "BigDecimal not recognized"); + assertEquals(0, BigInteger.valueOf(0).compareTo(jsonObject.getBigInteger("value")), "BigInteger not recognized"); } diff --git a/src/test/java/org/json/junit/JSONObjectLocaleTest.java b/src/test/java/org/json/junit/JSONObjectLocaleTest.java index 1cdaf743d..279e58f31 100755 --- a/src/test/java/org/json/junit/JSONObjectLocaleTest.java +++ b/src/test/java/org/json/junit/JSONObjectLocaleTest.java @@ -4,20 +4,20 @@ Public Domain. */ -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.*; import org.json.*; import org.json.junit.data.MyLocaleBean; -import org.junit.*; +import org.junit.jupiter.api.Test; /** * Note: This file is saved as UTF-8. Do not save as ASCII or the tests will * fail. * */ -public class JSONObjectLocaleTest { +class JSONObjectLocaleTest { /** * JSONObject built from a bean with locale-specific keys. * In the Turkish alphabet, there are 2 versions of the letter "i". @@ -32,7 +32,7 @@ public class JSONObjectLocaleTest { * regardless of the locale currently in effect. */ @Test - public void jsonObjectByLocaleBean() { + void jsonObjectByLocaleBean() { MyLocaleBean myLocaleBean = new MyLocaleBean(); @@ -42,9 +42,9 @@ public void jsonObjectByLocaleBean() { */ Locale.setDefault(new Locale("en")); JSONObject jsonen = new JSONObject(myLocaleBean); - assertEquals("expected size 2, found: " +jsonen.length(), 2, jsonen.length()); - assertEquals("expected jsonen[i] == beanI", "beanI", jsonen.getString("i")); - assertEquals("expected jsonen[id] == beanId", "beanId", jsonen.getString("id")); + assertEquals(2, jsonen.length(), "expected size 2, found: " +jsonen.length()); + assertEquals("beanI", jsonen.getString("i"), "expected jsonen[i] == beanI"); + assertEquals("beanId", jsonen.getString("id"), "expected jsonen[id] == beanId"); /** * Without the JSON-Java change, these keys would be stored internally as @@ -53,8 +53,8 @@ public void jsonObjectByLocaleBean() { */ Locale.setDefault(new Locale("tr")); JSONObject jsontr = new JSONObject(myLocaleBean); - assertEquals("expected size 2, found: " +jsontr.length(), 2, jsontr.length()); - assertEquals("expected jsontr[i] == beanI", "beanI", jsontr.getString("i")); - assertEquals("expected jsontr[id] == beanId", "beanId", jsontr.getString("id")); + assertEquals(2, jsontr.length(), "expected size 2, found: " +jsontr.length()); + assertEquals("beanI", jsontr.getString("i"), "expected jsontr[i] == beanI"); + assertEquals("beanId", jsontr.getString("id"), "expected jsontr[id] == beanId"); } } diff --git a/src/test/java/org/json/junit/JSONObjectNumberTest.java b/src/test/java/org/json/junit/JSONObjectNumberTest.java index 14e68d66b..46ca52d62 100644 --- a/src/test/java/org/json/junit/JSONObjectNumberTest.java +++ b/src/test/java/org/json/junit/JSONObjectNumberTest.java @@ -1,26 +1,19 @@ package org.json.junit; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - +import static org.junit.jupiter.api.Assertions.assertEquals; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.Collection; import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@RunWith(value = Parameterized.class) public class JSONObjectNumberTest { - private final String objectString; + private Integer value = 50; - @Parameters(name = "{index}: {0}") public static Collection data() { return Arrays.asList(new Object[][]{ {"{value:0050}", 1}, @@ -46,105 +39,138 @@ public static Collection data() { }); } - public JSONObjectNumberTest(String objectString, int resultIsNegative) { - this.objectString = objectString; + public void initJSONObjectNumberTest(String objectString, int resultIsNegative) { this.value *= resultIsNegative; + this.object = new JSONObject(objectString); } private JSONObject object; - @Before - public void setJsonObject() { - object = new JSONObject(objectString); - } - @Test - public void testGetNumber() { + + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void getNumber(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(value.intValue(), object.getNumber("value").intValue()); } - @Test - public void testGetBigDecimal() { - assertTrue(BigDecimal.valueOf(value).compareTo(object.getBigDecimal("value")) == 0); + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void getBigDecimal(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); + assertEquals(0, BigDecimal.valueOf(value).compareTo(object.getBigDecimal("value"))); } - @Test - public void testGetBigInteger() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void getBigInteger(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(BigInteger.valueOf(value), object.getBigInteger("value")); } - @Test - public void testGetFloat() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void getFloat(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(value.floatValue(), object.getFloat("value"), 0.0f); } - @Test - public void testGetDouble() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void getDouble(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(value.doubleValue(), object.getDouble("value"), 0.0d); } - @Test - public void testGetInt() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void getInt(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(value.intValue(), object.getInt("value")); } - @Test - public void testGetLong() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void getLong(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(value.longValue(), object.getLong("value")); } - @Test - public void testOptNumber() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optNumber(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(value.intValue(), object.optNumber("value").intValue()); } - @Test - public void testOptBigDecimal() { - assertTrue(BigDecimal.valueOf(value).compareTo(object.optBigDecimal("value", null)) == 0); + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optBigDecimal(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); + assertEquals(0, BigDecimal.valueOf(value).compareTo(object.optBigDecimal("value", null))); } - @Test - public void testOptBigInteger() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optBigInteger(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(BigInteger.valueOf(value), object.optBigInteger("value", null)); } - @Test - public void testOptFloat() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optFloat(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(value.floatValue(), object.optFloat("value"), 0.0f); } - @Test - public void testOptFloatObject() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optFloatObject(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals((Float) value.floatValue(), object.optFloatObject("value"), 0.0f); } - @Test - public void testOptDouble() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optDouble(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(value.doubleValue(), object.optDouble("value"), 0.0d); } - @Test - public void testOptDoubleObject() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optDoubleObject(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals((Double) value.doubleValue(), object.optDoubleObject("value"), 0.0d); } - @Test - public void testOptInt() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optInt(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(value.intValue(), object.optInt("value")); } - @Test - public void testOptIntegerObject() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optIntegerObject(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals((Integer) value.intValue(), object.optIntegerObject("value")); } - @Test - public void testOptLong() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optLong(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals(value.longValue(), object.optLong("value")); } - @Test - public void testOptLongObject() { + @MethodSource("data") + @ParameterizedTest(name = "{index}: {0}") + void optLongObject(String objectString, int resultIsNegative) { + initJSONObjectNumberTest(objectString, resultIsNegative); assertEquals((Long) value.longValue(), object.optLongObject("value")); } } diff --git a/src/test/java/org/json/junit/JSONObjectTest.java b/src/test/java/org/json/junit/JSONObjectTest.java index 96f36735d..bb69a6191 100644 --- a/src/test/java/org/json/junit/JSONObjectTest.java +++ b/src/test/java/org/json/junit/JSONObjectTest.java @@ -5,14 +5,7 @@ */ import static java.lang.Double.NaN; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -57,8 +50,8 @@ import org.json.junit.data.Singleton; import org.json.junit.data.SingletonEnum; import org.json.junit.data.WeirdList; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.JsonPath; @@ -80,7 +73,7 @@ public class JSONObjectTest { * Tests that the similar method is working as expected. */ @Test - public void verifySimilar() { + void verifySimilar() { final String string1 = "HasSameRef"; final String string2 = "HasDifferentRef"; JSONObject obj1 = new JSONObject() @@ -108,17 +101,17 @@ public void verifySimilar() { .put("key2", 2.0) .put("key3", new String(string2)); - assertFalse("obj1-obj2 Should eval to false", obj1.similar(obj2)); - assertTrue("obj1-obj3 Should eval to true", obj1.similar(obj3)); - assertTrue("obj1-obj4 Should eval to true", obj1.similar(obj4)); - assertFalse("obj1-obj5 Should eval to false", obj1.similar(obj5)); + assertFalse(obj1.similar(obj2), "obj1-obj2 Should eval to false"); + assertTrue(obj1.similar(obj3), "obj1-obj3 Should eval to true"); + assertTrue(obj1.similar(obj4), "obj1-obj4 Should eval to true"); + assertFalse(obj1.similar(obj5), "obj1-obj5 Should eval to false"); // verify that a double and big decimal are "similar" - assertTrue("should eval to true",new JSONObject().put("a",1.1d).similar(new JSONObject("{\"a\":1.1}"))); + assertTrue(new JSONObject().put("a",1.1d).similar(new JSONObject("{\"a\":1.1}")),"should eval to true"); // Confirm #618 is fixed (compare should not exit early if similar numbers are found) // Note that this test may not work if the JSONObject map entry order changes JSONObject first = new JSONObject("{\"a\": 1, \"b\": 2, \"c\": 3}"); JSONObject second = new JSONObject("{\"a\": 1, \"b\": 2.0, \"c\": 4}"); - assertFalse("first-second should eval to false", first.similar(second)); + assertFalse(first.similar(second), "first-second should eval to false"); List jsonObjects = new ArrayList( Arrays.asList(obj1, obj2, obj3, obj4, obj5) ); @@ -126,7 +119,7 @@ public void verifySimilar() { } @Test - public void timeNumberParsing() { + void timeNumberParsing() { // test data to use final String[] testData = new String[] { null, @@ -195,13 +188,15 @@ public void timeNumberParsing() { * Nothing good is expected to happen. * Expects NullPointerException */ - @Test(expected=NullPointerException.class) - public void jsonObjectByNullBean() { - JSONObject jsonObject = new JSONObject((MyBean)null); - assertNull("Expected an exception", jsonObject); - Util.checkJSONObjectMaps(jsonObject); + @Test + void jsonObjectByNullBean() { + assertThrows(NullPointerException.class, () -> { + JSONObject jsonObject = new JSONObject((MyBean)null); + assertNull(jsonObject, "Expected an exception"); + Util.checkJSONObjectMaps(jsonObject); + }); } - + /** * The JSON parser is permissive of unambiguous unquoted keys and values. * Such JSON text should be allowed, even if it does not strictly conform @@ -209,23 +204,23 @@ public void jsonObjectByNullBean() { * conforming JSON text. */ @Test - public void unquotedText() { + void unquotedText() { String str = "{key1:value1, key2:42, 1.2 : 3.4, -7e5 : something!}"; JSONObject jsonObject = new JSONObject(str); String textStr = jsonObject.toString(); - assertTrue("expected key1", textStr.contains("\"key1\"")); - assertTrue("expected value1", textStr.contains("\"value1\"")); - assertTrue("expected key2", textStr.contains("\"key2\"")); - assertTrue("expected 42", textStr.contains("42")); - assertTrue("expected 1.2", textStr.contains("\"1.2\"")); - assertTrue("expected 3.4", textStr.contains("3.4")); - assertTrue("expected -7E+5", textStr.contains("\"-7E+5\"")); - assertTrue("expected something!", textStr.contains("\"something!\"")); + assertTrue(textStr.contains("\"key1\""), "expected key1"); + assertTrue(textStr.contains("\"value1\""), "expected value1"); + assertTrue(textStr.contains("\"key2\""), "expected key2"); + assertTrue(textStr.contains("42"), "expected 42"); + assertTrue(textStr.contains("\"1.2\""), "expected 1.2"); + assertTrue(textStr.contains("3.4"), "expected 3.4"); + assertTrue(textStr.contains("\"-7E+5\""), "expected -7E+5"); + assertTrue(textStr.contains("\"something!\""), "expected something!"); Util.checkJSONObjectMaps(jsonObject); } - + @Test - public void testLongFromString(){ + void longFromString(){ String str = "26315000000253009"; JSONObject json = new JSONObject(); json.put("key", str); @@ -249,14 +244,14 @@ public void testLongFromString(){ + actualString + " expected " + str; Util.checkJSONObjectMaps(json); } - + /** * A JSONObject can be created with no content */ @Test - public void emptyJsonObject() { + void emptyJsonObject() { JSONObject jsonObject = new JSONObject(); - assertTrue("jsonObject should be empty", jsonObject.isEmpty()); + assertTrue(jsonObject.isEmpty(), "jsonObject should be empty"); Util.checkJSONObjectMaps(jsonObject); } @@ -266,7 +261,7 @@ public void emptyJsonObject() { * names list. */ @Test - public void jsonObjectByNames() { + void jsonObjectByNames() { String str = "{"+ "\"trueKey\":true,"+ @@ -283,11 +278,11 @@ public void jsonObjectByNames() { // validate JSON JSONObject jsonObjectByName = new JSONObject(jsonObject, keys); Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObjectByName.toString()); - assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObjectByName.query("/falseKey"))); - assertTrue("expected \"nullKey\":null", JSONObject.NULL.equals(jsonObjectByName.query("/nullKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObjectByName.query("/stringKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", new BigDecimal("-23.45e67").equals(jsonObjectByName.query("/doubleKey"))); + assertEquals(4, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 4 top level items"); + assertEquals(Boolean.FALSE, jsonObjectByName.query("/falseKey"), "expected \"falseKey\":false"); + assertEquals(JSONObject.NULL, jsonObjectByName.query("/nullKey"), "expected \"nullKey\":null"); + assertEquals("hello world!", jsonObjectByName.query("/stringKey"), "expected \"stringKey\":\"hello world!\""); + assertEquals(new BigDecimal("-23.45e67"), jsonObjectByName.query("/doubleKey"), "expected \"doubleKey\":-23.45e67"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList(jsonObject, jsonObjectByName))); } @@ -298,10 +293,10 @@ public void jsonObjectByNames() { * has full coverage from other tests. */ @Test - public void jsonObjectByNullMap() { + void jsonObjectByNullMap() { Map map = null; JSONObject jsonObject = new JSONObject(map); - assertTrue("jsonObject should be empty", jsonObject.isEmpty()); + assertTrue(jsonObject.isEmpty(), "jsonObject should be empty"); Util.checkJSONObjectMaps(jsonObject); } @@ -310,7 +305,7 @@ public void jsonObjectByNullMap() { * In this test all of the map entries are valid JSON types. */ @Test - public void jsonObjectByMap() { + void jsonObjectByMap() { Map map = new HashMap(); map.put("trueKey", Boolean.valueOf(true)); map.put("falseKey", Boolean.valueOf(false)); @@ -322,12 +317,12 @@ public void jsonObjectByMap() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); + assertEquals(6, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 6 top level items"); + assertEquals(Boolean.TRUE, jsonObject.query("/trueKey"), "expected \"trueKey\":true"); + assertEquals(Boolean.FALSE, jsonObject.query("/falseKey"), "expected \"falseKey\":false"); + assertEquals("hello world!", jsonObject.query("/stringKey"), "expected \"stringKey\":\"hello world!\""); + assertEquals("h\be\tllo w\u1234orld!", jsonObject.query("/escapeStringKey"), "expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\""); + assertEquals(Double.valueOf("-23.45e67"), jsonObject.query("/doubleKey"), "expected \"doubleKey\":-23.45e67"); Util.checkJSONObjectMaps(jsonObject); } @@ -335,7 +330,7 @@ public void jsonObjectByMap() { * Verifies that the constructor has backwards compatability with RAW types pre-java5. */ @Test - public void verifyConstructor() { + void verifyConstructor() { final JSONObject expected = new JSONObject("{\"myKey\":10}"); @@ -356,27 +351,27 @@ public void verifyConstructor() { JSONObject jaObjObj = new JSONObject(myCObjObj); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); + expected.similar(jaRaw), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); + expected.similar(jaStrObj), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); + expected.similar(jaStrInt), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); + expected.similar(jaObjObj), + "The RAW Collection should give me the same as the Typed Collection"); Util.checkJSONObjectsMaps(new ArrayList( Arrays.asList(jaRaw, jaStrObj, jaStrInt, jaObjObj)) ); } - + /** * Tests Number serialization. */ @Test - public void verifyNumberOutput(){ + void verifyNumberOutput(){ /** * MyNumberContainer is a POJO, so call JSONObject(bean), * which builds a map of getter names/values @@ -390,7 +385,7 @@ public void verifyNumberOutput(){ JSONObject jsonObject0 = new JSONObject(new MyNumberContainer()); String actual = jsonObject0.toString(); String expected = "{\"myNumber\":{\"number\":42}}"; - assertEquals("Equal", expected , actual); + assertEquals(expected , actual, "Equal"); /** * JSONObject.put() handles objects differently than the @@ -404,7 +399,7 @@ public void verifyNumberOutput(){ jsonObject1.put("myNumber", new MyNumber()); actual = jsonObject1.toString(); expected = "{\"myNumber\":42}"; - assertEquals("Equal", expected , actual); + assertEquals(expected , actual, "Equal"); /** * Calls the JSONObject(Map) ctor, which calls wrap() for values. @@ -417,7 +412,7 @@ public void verifyNumberOutput(){ JSONObject jsonObject2 = new JSONObject(Collections.singletonMap("myNumber", new AtomicInteger(42))); actual = jsonObject2.toString(); expected = "{\"myNumber\":\"42\"}"; - assertEquals("Equal", expected , actual); + assertEquals(expected , actual, "Equal"); /** * JSONObject.put() inserts the AtomicInteger directly into the @@ -429,7 +424,7 @@ public void verifyNumberOutput(){ jsonObject3.put("myNumber", new AtomicInteger(42)); actual = jsonObject3.toString(); expected = "{\"myNumber\":42}"; - assertEquals("Equal", expected , actual); + assertEquals(expected , actual, "Equal"); /** * Calls the JSONObject(Map) ctor, which calls wrap() for values. @@ -441,8 +436,8 @@ public void verifyNumberOutput(){ JSONObject jsonObject4 = new JSONObject(Collections.singletonMap("myNumber", new Fraction(4,2))); assertEquals(1, jsonObject4.length()); assertEquals(2, ((JSONObject)(jsonObject4.get("myNumber"))).length()); - assertEquals("Numerator", BigInteger.valueOf(4) , jsonObject4.query("/myNumber/numerator")); - assertEquals("Denominator", BigInteger.valueOf(2) , jsonObject4.query("/myNumber/denominator")); + assertEquals(BigInteger.valueOf(4) , jsonObject4.query("/myNumber/numerator"), "Numerator"); + assertEquals(BigInteger.valueOf(2) , jsonObject4.query("/myNumber/denominator"), "Denominator"); /** * JSONObject.put() inserts the Fraction directly into the @@ -456,7 +451,7 @@ public void verifyNumberOutput(){ jsonObject5.put("myNumber", new Fraction(4,2)); actual = jsonObject5.toString(); expected = "{\"myNumber\":\"4/2\"}"; // valid JSON, bug fixed - assertEquals("Equal", expected , actual); + assertEquals(expected , actual, "Equal"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jsonObject0, jsonObject1, jsonObject2, jsonObject3, jsonObject4, jsonObject5 @@ -467,7 +462,7 @@ public void verifyNumberOutput(){ * Verifies that the put Collection has backwards compatibility with RAW types pre-java5. */ @Test - public void verifyPutCollection() { + void verifyPutCollection() { final JSONObject expected = new JSONObject("{\"myCollection\":[10]}"); @@ -487,26 +482,26 @@ public void verifyPutCollection() { jaInt.put("myCollection", myCInt); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); + expected.similar(jaRaw), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObj)); + expected.similar(jaObj), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaInt)); + expected.similar(jaInt), + "The RAW Collection should give me the same as the Typed Collection"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jaRaw, jaObj, jaInt ))); } - + /** * Verifies that the put Map has backwards compatibility with RAW types pre-java5. */ @Test - public void verifyPutMap() { + void verifyPutMap() { final JSONObject expected = new JSONObject("{\"myMap\":{\"myKey\":10}}"); @@ -531,17 +526,17 @@ public void verifyPutMap() { jaObjObj.put("myMap", myCObjObj); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaRaw)); + expected.similar(jaRaw), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrObj)); + expected.similar(jaStrObj), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaStrInt)); + expected.similar(jaStrInt), + "The RAW Collection should give me the same as the Typed Collection"); assertTrue( - "The RAW Collection should give me the same as the Typed Collection", - expected.similar(jaObjObj)); + expected.similar(jaObjObj), + "The RAW Collection should give me the same as the Typed Collection"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jaRaw, jaStrObj, jaStrInt, jaStrObj @@ -555,7 +550,7 @@ public void verifyPutMap() { * The actual conversion is kind of interesting. */ @Test - public void jsonObjectByMapWithUnsupportedValues() { + void jsonObjectByMapWithUnsupportedValues() { Map jsonMap = new HashMap(); // Just insert some random objects jsonMap.put("key1", new CDL()); @@ -565,9 +560,9 @@ public void jsonObjectByMapWithUnsupportedValues() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected 0 key1 items", ((Map)(JsonPath.read(doc, "$.key1"))).size() == 0); - assertTrue("expected \"key2\":java.lang.Exception","java.lang.Exception".equals(jsonObject.query("/key2"))); + assertEquals(2, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 2 top level items"); + assertEquals(0, ((Map)(JsonPath.read(doc, "$.key1"))).size(), "expected 0 key1 items"); + assertEquals("java.lang.Exception", jsonObject.query("/key2"), "expected \"key2\":java.lang.Exception"); Util.checkJSONObjectMaps(jsonObject); } @@ -576,7 +571,7 @@ public void jsonObjectByMapWithUnsupportedValues() { * In this test one of the map values is null */ @Test - public void jsonObjectByMapWithNullValue() { + void jsonObjectByMapWithNullValue() { Map map = new HashMap(); map.put("trueKey", Boolean.valueOf(true)); map.put("falseKey", Boolean.valueOf(false)); @@ -589,13 +584,13 @@ public void jsonObjectByMapWithNullValue() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected \"trueKey\":true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); - assertTrue("expected \"falseKey\":false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); - assertTrue("expected \"stringKey\":\"hello world!\"", "hello world!".equals(jsonObject.query("/stringKey"))); - assertTrue("expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\"", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); - assertTrue("expected \"intKey\":42", Long.valueOf("42").equals(jsonObject.query("/intKey"))); - assertTrue("expected \"doubleKey\":-23.45e67", Double.valueOf("-23.45e67").equals(jsonObject.query("/doubleKey"))); + assertEquals(6, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 6 top level items"); + assertEquals(Boolean.TRUE, jsonObject.query("/trueKey"), "expected \"trueKey\":true"); + assertEquals(Boolean.FALSE, jsonObject.query("/falseKey"), "expected \"falseKey\":false"); + assertEquals("hello world!", jsonObject.query("/stringKey"), "expected \"stringKey\":\"hello world!\""); + assertEquals("h\be\tllo w\u1234orld!", jsonObject.query("/escapeStringKey"), "expected \"escapeStringKey\":\"h\be\tllo w\u1234orld!\""); + assertEquals(Long.valueOf("42"), jsonObject.query("/intKey"), "expected \"intKey\":42"); + assertEquals(Double.valueOf("-23.45e67"), jsonObject.query("/doubleKey"), "expected \"doubleKey\":-23.45e67"); Util.checkJSONObjectMaps(jsonObject); } @@ -605,7 +600,7 @@ public void jsonObjectByMapWithNullValue() { */ @SuppressWarnings("boxing") @Test - public void jsonObjectByBean1() { + void jsonObjectByBean1() { /** * Default access classes have to be mocked since JSONObject, which is * not in the same package, cannot call MyBean methods by reflection. @@ -625,18 +620,17 @@ public void jsonObjectByBean1() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 8 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 8); - assertTrue("expected 0 items in stringReaderKey", ((Map) (JsonPath.read(doc, "$.stringReaderKey"))).size() == 0); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); - assertTrue("expected hello world!","hello world!".equals(jsonObject.query("/stringKey"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/escapeStringKey"))); - assertTrue("expected 42", Integer.valueOf("42").equals(jsonObject.query("/intKey"))); - assertTrue("expected -23.45e7", Double.valueOf("-23.45e7").equals(jsonObject.query("/doubleKey"))); + assertEquals(8, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 8 top level items"); + assertEquals(0, ((Map)(JsonPath.read(doc, "$.stringReaderKey"))).size(), "expected 0 items in stringReaderKey"); + assertEquals(Boolean.TRUE, jsonObject.query("/trueKey"), "expected true"); + assertEquals(Boolean.FALSE, jsonObject.query("/falseKey"), "expected false"); + assertEquals("hello world!", jsonObject.query("/stringKey"), "expected hello world!"); + assertEquals("h\be\tllo w\u1234orld!", jsonObject.query("/escapeStringKey"), "expected h\be\tllo w\u1234orld!"); + assertEquals(Integer.valueOf("42"), jsonObject.query("/intKey"), "expected 42"); + assertEquals(Double.valueOf("-23.45e7"), jsonObject.query("/doubleKey"), "expected -23.45e7"); // sorry, mockito artifact - assertTrue("expected 2 mockitoInterceptor items", ((Map)(JsonPath.read(doc, "$.mockitoInterceptor"))).size() == 2); - assertTrue("expected 0 mockitoInterceptor.serializationSupport items", - ((Map)(JsonPath.read(doc, "$.mockitoInterceptor.serializationSupport"))).size() == 0); + assertEquals(2, ((Map)(JsonPath.read(doc, "$.mockitoInterceptor"))).size(), "expected 2 mockitoInterceptor items"); + assertEquals(0, ((Map)(JsonPath.read(doc, "$.mockitoInterceptor.serializationSupport"))).size(), "expected 0 mockitoInterceptor.serializationSupport items"); Util.checkJSONObjectMaps(jsonObject); } @@ -644,86 +638,86 @@ public void jsonObjectByBean1() { * JSONObject built from a bean that has custom field names. */ @Test - public void jsonObjectByBean2() { + void jsonObjectByBean2() { JSONObject jsonObject = new JSONObject(new MyBeanCustomName()); assertNotNull(jsonObject); - assertEquals("Wrong number of keys found:", - 5, - jsonObject.keySet().size()); - assertFalse("Normal field name (someString) processing did not work", - jsonObject.has("someString")); - assertFalse("Normal field name (myDouble) processing did not work", - jsonObject.has("myDouble")); - assertFalse("Normal field name (someFloat) processing did not work", - jsonObject.has("someFloat")); - assertFalse("Ignored field not found!", - jsonObject.has("ignoredInt")); + assertEquals(5, + jsonObject.keySet().size(), + "Wrong number of keys found:"); + assertFalse(jsonObject.has("someString"), + "Normal field name (someString) processing did not work"); + assertFalse(jsonObject.has("myDouble"), + "Normal field name (myDouble) processing did not work"); + assertFalse(jsonObject.has("someFloat"), + "Normal field name (someFloat) processing did not work"); + assertFalse(jsonObject.has("ignoredInt"), + "Ignored field not found!"); // getSomeInt() has no user-defined annotation - assertTrue("Normal field name (someInt) should have been found", - jsonObject.has("someInt")); + assertTrue(jsonObject.has("someInt"), + "Normal field name (someInt) should have been found"); // the user-defined annotation does not replace any value, so someLong should be found - assertTrue("Normal field name (someLong) should have been found", - jsonObject.has("someLong")); + assertTrue(jsonObject.has("someLong"), + "Normal field name (someLong) should have been found"); // myStringField replaces someString property name via user-defined annotation - assertTrue("Overridden String field name (myStringField) should have been found", - jsonObject.has("myStringField")); + assertTrue(jsonObject.has("myStringField"), + "Overridden String field name (myStringField) should have been found"); // weird name replaces myDouble property name via user-defined annotation - assertTrue("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) should have been found", - jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!")); + assertTrue(jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!"), + "Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) should have been found"); // InterfaceField replaces someFloat property name via user-defined annotation - assertTrue("Overridden String field name (InterfaceField) should have been found", - jsonObject.has("InterfaceField")); + assertTrue(jsonObject.has("InterfaceField"), + "Overridden String field name (InterfaceField) should have been found"); Util.checkJSONObjectMaps(jsonObject); } - + /** * JSONObject built from a bean that has custom field names inherited from a parent class. */ @Test - public void jsonObjectByBean3() { + void jsonObjectByBean3() { JSONObject jsonObject = new JSONObject(new MyBeanCustomNameSubClass()); assertNotNull(jsonObject); - assertEquals("Wrong number of keys found:", - 7, - jsonObject.keySet().size()); - assertFalse("Normal int field name (someInt) found, but was overridden", - jsonObject.has("someInt")); - assertFalse("Normal field name (myDouble) processing did not work", - jsonObject.has("myDouble")); + assertEquals(7, + jsonObject.keySet().size(), + "Wrong number of keys found:"); + assertFalse(jsonObject.has("someInt"), + "Normal int field name (someInt) found, but was overridden"); + assertFalse(jsonObject.has("myDouble"), + "Normal field name (myDouble) processing did not work"); // myDouble was replaced by weird name, and then replaced again by AMoreNormalName via user-defined annotation - assertFalse("Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) should not be FOUND!", - jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!")); - assertFalse("Normal field name (someFloat) found, but was overridden", - jsonObject.has("someFloat")); - assertFalse("Ignored field found! but was overridden", - jsonObject.has("ignoredInt")); + assertFalse(jsonObject.has("Some Weird NAme that Normally Wouldn't be possible!"), + "Overridden String field name (Some Weird NAme that Normally Wouldn't be possible!) should not be FOUND!"); + assertFalse(jsonObject.has("someFloat"), + "Normal field name (someFloat) found, but was overridden"); + assertFalse(jsonObject.has("ignoredInt"), + "Ignored field found! but was overridden"); // shouldNotBeJSON property name was first ignored, then replaced by ShouldBeIgnored via user-defined annotations - assertFalse("Ignored field at the same level as forced name should not have been found", - jsonObject.has("ShouldBeIgnored")); + assertFalse(jsonObject.has("ShouldBeIgnored"), + "Ignored field at the same level as forced name should not have been found"); // able property name was replaced by Getable via user-defined annotation - assertFalse("Normally ignored field (able) with explicit property name should not have been found", - jsonObject.has("able")); + assertFalse(jsonObject.has("able"), + "Normally ignored field (able) with explicit property name should not have been found"); // property name someInt was replaced by newIntFieldName via user-defined annotation - assertTrue("Overridden int field name (newIntFieldName) should have been found", - jsonObject.has("newIntFieldName")); + assertTrue(jsonObject.has("newIntFieldName"), + "Overridden int field name (newIntFieldName) should have been found"); // property name someLong was not replaced via user-defined annotation - assertTrue("Normal field name (someLong) should have been found", - jsonObject.has("someLong")); + assertTrue(jsonObject.has("someLong"), + "Normal field name (someLong) should have been found"); // property name someString was replaced by myStringField via user-defined annotation - assertTrue("Overridden String field name (myStringField) should have been found", - jsonObject.has("myStringField")); + assertTrue(jsonObject.has("myStringField"), + "Overridden String field name (myStringField) should have been found"); // property name myDouble was replaced by a weird name, followed by AMoreNormalName via user-defined annotations - assertTrue("Overridden double field name (AMoreNormalName) should have been found", - jsonObject.has("AMoreNormalName")); + assertTrue(jsonObject.has("AMoreNormalName"), + "Overridden double field name (AMoreNormalName) should have been found"); // property name someFloat was replaced by InterfaceField via user-defined annotation - assertTrue("Overridden String field name (InterfaceField) should have been found", - jsonObject.has("InterfaceField")); + assertTrue(jsonObject.has("InterfaceField"), + "Overridden String field name (InterfaceField) should have been found"); // property name ignoredInt was replaced by none, followed by forcedInt via user-defined annotations - assertTrue("Forced field should have been found!", - jsonObject.has("forcedInt")); + assertTrue(jsonObject.has("forcedInt"), + "Forced field should have been found!"); // property name able was replaced by Getable via user-defined annotation - assertTrue("Overridden boolean field name (Getable) should have been found", - jsonObject.has("Getable")); + assertTrue(jsonObject.has("Getable"), + "Overridden boolean field name (Getable) should have been found"); Util.checkJSONObjectMaps(jsonObject); } @@ -734,7 +728,7 @@ public void jsonObjectByBean3() { * data members, which have been added to the class. */ @Test - public void jsonObjectByObjectAndNames() { + void jsonObjectByObjectAndNames() { String[] keys = {"publicString", "publicInt"}; // just need a class that has public data members MyPublicClass myPublicClass = new MyPublicClass(); @@ -742,9 +736,9 @@ public void jsonObjectByObjectAndNames() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected \"publicString\":\"abc\"", "abc".equals(jsonObject.query("/publicString"))); - assertTrue("expected \"publicInt\":42", Integer.valueOf(42).equals(jsonObject.query("/publicInt"))); + assertEquals(2, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 2 top level items"); + assertEquals("abc", jsonObject.query("/publicString"), "expected \"publicString\":\"abc\""); + assertEquals(Integer.valueOf(42), jsonObject.query("/publicInt"), "expected \"publicInt\":42"); Util.checkJSONObjectMaps(jsonObject); } @@ -753,29 +747,29 @@ public void jsonObjectByObjectAndNames() { * The test resource bundle is uncomplicated, but provides adequate test coverage. */ @Test - public void jsonObjectByResourceBundle() { + void jsonObjectByResourceBundle() { JSONObject jsonObject = new JSONObject("org.json.junit.data.StringsResourceBundle", Locale.getDefault()); // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 2 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 2); - assertTrue("expected 2 greetings items", ((Map)(JsonPath.read(doc, "$.greetings"))).size() == 2); - assertTrue("expected \"hello\":\"Hello, \"", "Hello, ".equals(jsonObject.query("/greetings/hello"))); - assertTrue("expected \"world\":\"World!\"", "World!".equals(jsonObject.query("/greetings/world"))); - assertTrue("expected 2 farewells items", ((Map)(JsonPath.read(doc, "$.farewells"))).size() == 2); - assertTrue("expected \"later\":\"Later, \"", "Later, ".equals(jsonObject.query("/farewells/later"))); - assertTrue("expected \"world\":\"World!\"", "Alligator!".equals(jsonObject.query("/farewells/gator"))); + assertEquals(2, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 2 top level items"); + assertEquals(2, ((Map)(JsonPath.read(doc, "$.greetings"))).size(), "expected 2 greetings items"); + assertEquals("Hello, ", jsonObject.query("/greetings/hello"), "expected \"hello\":\"Hello, \""); + assertEquals("World!", jsonObject.query("/greetings/world"), "expected \"world\":\"World!\""); + assertEquals(2, ((Map)(JsonPath.read(doc, "$.farewells"))).size(), "expected 2 farewells items"); + assertEquals("Later, ", jsonObject.query("/farewells/later"), "expected \"later\":\"Later, \""); + assertEquals("Alligator!", jsonObject.query("/farewells/gator"), "expected \"world\":\"World!\""); Util.checkJSONObjectMaps(jsonObject); } - + /** * Exercise the JSONObject.accumulate() method */ @SuppressWarnings("boxing") @Test - public void jsonObjectAccumulate() { + void jsonObjectAccumulate() { JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("myArray", true); @@ -792,14 +786,14 @@ public void jsonObjectAccumulate() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1"))); - assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); - assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); - assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); + assertEquals(1, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 1 top level item"); + assertEquals(6, ((List)(JsonPath.read(doc, "$.myArray"))).size(), "expected 6 myArray items"); + assertEquals(Boolean.TRUE, jsonObject.query("/myArray/0"), "expected true"); + assertEquals(Boolean.FALSE, jsonObject.query("/myArray/1"), "expected false"); + assertEquals("hello world!", jsonObject.query("/myArray/2"), "expected hello world!"); + assertEquals("h\be\tllo w\u1234orld!", jsonObject.query("/myArray/3"), "expected h\be\tllo w\u1234orld!"); + assertEquals(Integer.valueOf(42), jsonObject.query("/myArray/4"), "expected 42"); + assertEquals(Double.valueOf(-23.45e7), jsonObject.query("/myArray/5"), "expected -23.45e7"); Util.checkJSONObjectMaps(jsonObject); } @@ -808,7 +802,7 @@ public void jsonObjectAccumulate() { */ @SuppressWarnings("boxing") @Test - public void jsonObjectAppend() { + void jsonObjectAppend() { JSONObject jsonObject = new JSONObject(); jsonObject.append("myArray", true); jsonObject.append("myArray", false); @@ -824,14 +818,14 @@ public void jsonObjectAppend() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 6 myArray items", ((List)(JsonPath.read(doc, "$.myArray"))).size() == 6); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/myArray/0"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/myArray/1"))); - assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/myArray/2"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/myArray/3"))); - assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/myArray/4"))); - assertTrue("expected -23.45e7", Double.valueOf(-23.45e7).equals(jsonObject.query("/myArray/5"))); + assertEquals(1, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 1 top level item"); + assertEquals(6, ((List)(JsonPath.read(doc, "$.myArray"))).size(), "expected 6 myArray items"); + assertEquals(Boolean.TRUE, jsonObject.query("/myArray/0"), "expected true"); + assertEquals(Boolean.FALSE, jsonObject.query("/myArray/1"), "expected false"); + assertEquals("hello world!", jsonObject.query("/myArray/2"), "expected hello world!"); + assertEquals("h\be\tllo w\u1234orld!", jsonObject.query("/myArray/3"), "expected h\be\tllo w\u1234orld!"); + assertEquals(Integer.valueOf(42), jsonObject.query("/myArray/4"), "expected 42"); + assertEquals(Double.valueOf(-23.45e7), jsonObject.query("/myArray/5"), "expected -23.45e7"); Util.checkJSONObjectMaps(jsonObject); } @@ -840,15 +834,14 @@ public void jsonObjectAppend() { */ @SuppressWarnings("boxing") @Test - public void jsonObjectDoubleToString() { + void jsonObjectDoubleToString() { String [] expectedStrs = {"1", "1", "-23.4", "-2.345E68", "null", "null" }; Double [] doubles = { 1.0, 00001.00000, -23.4, -23.45e67, NaN, Double.NEGATIVE_INFINITY }; for (int i = 0; i < expectedStrs.length; ++i) { String actualStr = JSONObject.doubleToString(doubles[i]); - assertTrue("value expected ["+expectedStrs[i]+ - "] found ["+actualStr+ "]", - expectedStrs[i].equals(actualStr)); + assertEquals(expectedStrs[i], actualStr, "value expected [" + expectedStrs[i] + + "] found [" + actualStr + "]"); } } @@ -856,7 +849,7 @@ public void jsonObjectDoubleToString() { * Exercise some JSONObject get[type] and opt[type] methods */ @Test - public void jsonObjectValues() { + void jsonObjectValues() { String str = "{"+ "\"trueKey\":true,"+ @@ -877,119 +870,85 @@ public void jsonObjectValues() { "\"objectKey\":{\"myKey\":\"myVal\"}"+ "}"; JSONObject jsonObject = new JSONObject(str); - assertTrue("trueKey should be true", jsonObject.getBoolean("trueKey")); - assertTrue("opt trueKey should be true", jsonObject.optBoolean("trueKey")); - assertTrue("opt trueKey should be true", jsonObject.optBooleanObject("trueKey")); - assertTrue("falseKey should be false", !jsonObject.getBoolean("falseKey")); - assertTrue("trueStrKey should be true", jsonObject.getBoolean("trueStrKey")); - assertTrue("trueStrKey should be true", jsonObject.optBoolean("trueStrKey")); - assertTrue("trueStrKey should be true", jsonObject.optBooleanObject("trueStrKey")); - assertTrue("falseStrKey should be false", !jsonObject.getBoolean("falseStrKey")); - assertTrue("stringKey should be string", - jsonObject.getString("stringKey").equals("hello world!")); - assertTrue("doubleKey should be double", - jsonObject.getDouble("doubleKey") == -23.45e7); - assertTrue("doubleStrKey should be double", - jsonObject.getDouble("doubleStrKey") == 1); - assertTrue("doubleKey can be float", - jsonObject.getFloat("doubleKey") == -23.45e7f); - assertTrue("doubleStrKey can be float", - jsonObject.getFloat("doubleStrKey") == 1f); - assertTrue("opt doubleKey should be double", - jsonObject.optDouble("doubleKey") == -23.45e7); - assertTrue("opt doubleKey with Default should be double", - jsonObject.optDouble("doubleStrKey", NaN) == 1); - assertTrue("opt doubleKey should be Double", - Double.valueOf(-23.45e7).equals(jsonObject.optDoubleObject("doubleKey"))); - assertTrue("opt doubleKey with Default should be Double", - Double.valueOf(1).equals(jsonObject.optDoubleObject("doubleStrKey", NaN))); - assertTrue("opt negZeroKey should be a Double", - jsonObject.opt("negZeroKey") instanceof Double); - assertTrue("get negZeroKey should be a Double", - jsonObject.get("negZeroKey") instanceof Double); - assertTrue("optNumber negZeroKey should return Double", - jsonObject.optNumber("negZeroKey") instanceof Double); - assertTrue("optNumber negZeroStrKey should return Double", - jsonObject.optNumber("negZeroStrKey") instanceof Double); - assertTrue("opt negZeroKey should be double", - Double.compare(jsonObject.optDouble("negZeroKey"), -0.0d) == 0); - assertTrue("opt negZeroStrKey with Default should be double", - Double.compare(jsonObject.optDouble("negZeroStrKey"), -0.0d) == 0); - assertTrue("opt negZeroKey should be Double", - Double.valueOf(-0.0d).equals(jsonObject.optDoubleObject("negZeroKey"))); - assertTrue("opt negZeroStrKey with Default should be Double", - Double.valueOf(-0.0d).equals(jsonObject.optDoubleObject("negZeroStrKey"))); - assertTrue("optNumber negZeroKey should be -0.0", - Double.compare(jsonObject.optNumber("negZeroKey").doubleValue(), -0.0d) == 0); - assertTrue("optNumber negZeroStrKey should be -0.0", - Double.compare(jsonObject.optNumber("negZeroStrKey").doubleValue(), -0.0d) == 0); - assertTrue("optFloat doubleKey should be float", - jsonObject.optFloat("doubleKey") == -23.45e7f); - assertTrue("optFloat doubleKey with Default should be float", - jsonObject.optFloat("doubleStrKey", Float.NaN) == 1f); - assertTrue("optFloat doubleKey should be Float", - Float.valueOf(-23.45e7f).equals(jsonObject.optFloatObject("doubleKey"))); - assertTrue("optFloat doubleKey with Default should be Float", - Float.valueOf(1f).equals(jsonObject.optFloatObject("doubleStrKey", Float.NaN))); - assertTrue("intKey should be int", - jsonObject.optInt("intKey") == 42); - assertTrue("opt intKey should be int", - jsonObject.optInt("intKey", 0) == 42); - assertTrue("intKey should be Integer", - Integer.valueOf(42).equals(jsonObject.optIntegerObject("intKey"))); - assertTrue("opt intKey should be Integer", - Integer.valueOf(42).equals(jsonObject.optIntegerObject("intKey", 0))); - assertTrue("opt intKey with default should be int", - jsonObject.getInt("intKey") == 42); - assertTrue("intStrKey should be int", - jsonObject.getInt("intStrKey") == 43); - assertTrue("longKey should be long", - jsonObject.getLong("longKey") == 1234567890123456789L); - assertTrue("opt longKey should be long", - jsonObject.optLong("longKey") == 1234567890123456789L); - assertTrue("opt longKey with default should be long", - jsonObject.optLong("longKey", 0) == 1234567890123456789L); - assertTrue("opt longKey should be Long", - Long.valueOf(1234567890123456789L).equals(jsonObject.optLongObject("longKey"))); - assertTrue("opt longKey with default should be Long", - Long.valueOf(1234567890123456789L).equals(jsonObject.optLongObject("longKey", 0L))); - assertTrue("longStrKey should be long", - jsonObject.getLong("longStrKey") == 987654321098765432L); - assertTrue("optNumber int should return Integer", - jsonObject.optNumber("intKey") instanceof Integer); - assertTrue("optNumber long should return Long", - jsonObject.optNumber("longKey") instanceof Long); - assertTrue("optNumber double should return BigDecimal", - jsonObject.optNumber("doubleKey") instanceof BigDecimal); - assertTrue("optNumber Str int should return Integer", - jsonObject.optNumber("intStrKey") instanceof Integer); - assertTrue("optNumber Str long should return Long", - jsonObject.optNumber("longStrKey") instanceof Long); - assertTrue("optNumber Str double should return BigDecimal", - jsonObject.optNumber("doubleStrKey") instanceof BigDecimal); - assertTrue("optNumber BigDecimalStrKey should return BigDecimal", - jsonObject.optNumber("BigDecimalStrKey") instanceof BigDecimal); - assertTrue("xKey should not exist", - jsonObject.isNull("xKey")); - assertTrue("stringKey should exist", - jsonObject.has("stringKey")); - assertTrue("opt stringKey should string", - jsonObject.optString("stringKey").equals("hello world!")); - assertTrue("opt stringKey with default should string", - jsonObject.optString("stringKey", "not found").equals("hello world!")); + assertTrue(jsonObject.getBoolean("trueKey"), "trueKey should be true"); + assertTrue(jsonObject.optBoolean("trueKey"), "opt trueKey should be true"); + assertTrue(jsonObject.optBooleanObject("trueKey"), "opt trueKey should be true"); + assertFalse(jsonObject.getBoolean("falseKey"), "falseKey should be false"); + assertTrue(jsonObject.getBoolean("trueStrKey"), "trueStrKey should be true"); + assertTrue(jsonObject.optBoolean("trueStrKey"), "trueStrKey should be true"); + assertTrue(jsonObject.optBooleanObject("trueStrKey"), "trueStrKey should be true"); + assertFalse(jsonObject.getBoolean("falseStrKey"), "falseStrKey should be false"); + assertEquals("hello world!", jsonObject.getString("stringKey"), "stringKey should be string"); + assertEquals(jsonObject.getDouble("doubleKey"), -23.45e7, "doubleKey should be double"); + assertEquals(1, jsonObject.getDouble("doubleStrKey"), "doubleStrKey should be double"); + assertEquals(jsonObject.getFloat("doubleKey"), -23.45e7f, "doubleKey can be float"); + assertEquals(1f, jsonObject.getFloat("doubleStrKey"), "doubleStrKey can be float"); + assertEquals(jsonObject.optDouble("doubleKey"), -23.45e7, "opt doubleKey should be double"); + assertEquals(1, jsonObject.optDouble("doubleStrKey", NaN), "opt doubleKey with Default should be double"); + assertEquals(Double.valueOf(-23.45e7), jsonObject.optDoubleObject("doubleKey"), "opt doubleKey should be Double"); + assertEquals(Double.valueOf(1), jsonObject.optDoubleObject("doubleStrKey", NaN), "opt doubleKey with Default should be Double"); + assertTrue(jsonObject.opt("negZeroKey") instanceof Double, + "opt negZeroKey should be a Double"); + assertTrue(jsonObject.get("negZeroKey") instanceof Double, + "get negZeroKey should be a Double"); + assertTrue(jsonObject.optNumber("negZeroKey") instanceof Double, + "optNumber negZeroKey should return Double"); + assertTrue(jsonObject.optNumber("negZeroStrKey") instanceof Double, + "optNumber negZeroStrKey should return Double"); + assertEquals(0, Double.compare(jsonObject.optDouble("negZeroKey"), -0.0d), "opt negZeroKey should be double"); + assertEquals(0, Double.compare(jsonObject.optDouble("negZeroStrKey"), -0.0d), "opt negZeroStrKey with Default should be double"); + assertEquals(Double.valueOf(-0.0d), jsonObject.optDoubleObject("negZeroKey"), "opt negZeroKey should be Double"); + assertEquals(Double.valueOf(-0.0d), jsonObject.optDoubleObject("negZeroStrKey"), "opt negZeroStrKey with Default should be Double"); + assertEquals(0, Double.compare(jsonObject.optNumber("negZeroKey").doubleValue(), -0.0d), "optNumber negZeroKey should be -0.0"); + assertEquals(0, Double.compare(jsonObject.optNumber("negZeroStrKey").doubleValue(), -0.0d), "optNumber negZeroStrKey should be -0.0"); + assertEquals(jsonObject.optFloat("doubleKey"), -23.45e7f, "optFloat doubleKey should be float"); + assertEquals(1f, jsonObject.optFloat("doubleStrKey", Float.NaN), "optFloat doubleKey with Default should be float"); + assertEquals(Float.valueOf(-23.45e7f), jsonObject.optFloatObject("doubleKey"), "optFloat doubleKey should be Float"); + assertEquals(Float.valueOf(1f), jsonObject.optFloatObject("doubleStrKey", Float.NaN), "optFloat doubleKey with Default should be Float"); + assertEquals(42, jsonObject.optInt("intKey"), "intKey should be int"); + assertEquals(42, jsonObject.optInt("intKey", 0), "opt intKey should be int"); + assertEquals(Integer.valueOf(42), jsonObject.optIntegerObject("intKey"), "intKey should be Integer"); + assertEquals(Integer.valueOf(42), jsonObject.optIntegerObject("intKey", 0), "opt intKey should be Integer"); + assertEquals(42, jsonObject.getInt("intKey"), "opt intKey with default should be int"); + assertEquals(43, jsonObject.getInt("intStrKey"), "intStrKey should be int"); + assertEquals(1234567890123456789L, jsonObject.getLong("longKey"), "longKey should be long"); + assertEquals(1234567890123456789L, jsonObject.optLong("longKey"), "opt longKey should be long"); + assertEquals(1234567890123456789L, jsonObject.optLong("longKey", 0), "opt longKey with default should be long"); + assertEquals(Long.valueOf(1234567890123456789L), jsonObject.optLongObject("longKey"), "opt longKey should be Long"); + assertEquals(Long.valueOf(1234567890123456789L), jsonObject.optLongObject("longKey", 0L), "opt longKey with default should be Long"); + assertEquals(987654321098765432L, jsonObject.getLong("longStrKey"), "longStrKey should be long"); + assertTrue(jsonObject.optNumber("intKey") instanceof Integer, + "optNumber int should return Integer"); + assertTrue(jsonObject.optNumber("longKey") instanceof Long, + "optNumber long should return Long"); + assertTrue(jsonObject.optNumber("doubleKey") instanceof BigDecimal, + "optNumber double should return BigDecimal"); + assertTrue(jsonObject.optNumber("intStrKey") instanceof Integer, + "optNumber Str int should return Integer"); + assertTrue(jsonObject.optNumber("longStrKey") instanceof Long, + "optNumber Str long should return Long"); + assertTrue(jsonObject.optNumber("doubleStrKey") instanceof BigDecimal, + "optNumber Str double should return BigDecimal"); + assertTrue(jsonObject.optNumber("BigDecimalStrKey") instanceof BigDecimal, + "optNumber BigDecimalStrKey should return BigDecimal"); + assertTrue(jsonObject.isNull("xKey"), + "xKey should not exist"); + assertTrue(jsonObject.has("stringKey"), + "stringKey should exist"); + assertEquals("hello world!", jsonObject.optString("stringKey"), "opt stringKey should string"); + assertEquals("hello world!", jsonObject.optString("stringKey", "not found"), "opt stringKey with default should string"); JSONArray jsonArray = jsonObject.getJSONArray("arrayKey"); - assertTrue("arrayKey should be JSONArray", - jsonArray.getInt(0) == 0 && + assertTrue(jsonArray.getInt(0) == 0 && jsonArray.getInt(1) == 1 && - jsonArray.getInt(2) == 2); + jsonArray.getInt(2) == 2, + "arrayKey should be JSONArray"); jsonArray = jsonObject.optJSONArray("arrayKey"); - assertTrue("opt arrayKey should be JSONArray", - jsonArray.getInt(0) == 0 && + assertTrue(jsonArray.getInt(0) == 0 && jsonArray.getInt(1) == 1 && - jsonArray.getInt(2) == 2); + jsonArray.getInt(2) == 2, + "opt arrayKey should be JSONArray"); JSONObject jsonObjectInner = jsonObject.getJSONObject("objectKey"); - assertTrue("objectKey should be JSONObject", - jsonObjectInner.get("myKey").equals("myVal")); + assertEquals("myVal", jsonObjectInner.get("myKey"), "objectKey should be JSONObject"); Util.checkJSONObjectMaps(jsonObject); } @@ -997,32 +956,30 @@ public void jsonObjectValues() { * Check whether JSONObject handles large or high precision numbers correctly */ @Test - public void stringToValueNumbersTest() { - assertTrue("-0 Should be a Double!",JSONObject.stringToValue("-0") instanceof Double); - assertTrue("-0.0 Should be a Double!",JSONObject.stringToValue("-0.0") instanceof Double); - assertTrue("'-' Should be a String!",JSONObject.stringToValue("-") instanceof String); - assertTrue( "0.2 should be a BigDecimal!", - JSONObject.stringToValue( "0.2" ) instanceof BigDecimal ); - assertTrue( "Doubles should be BigDecimal, even when incorrectly converting floats!", - JSONObject.stringToValue( Double.valueOf( "0.2f" ).toString() ) instanceof BigDecimal ); + void stringToValueNumbersTest() { + assertTrue(JSONObject.stringToValue("-0") instanceof Double,"-0 Should be a Double!"); + assertTrue(JSONObject.stringToValue("-0.0") instanceof Double,"-0.0 Should be a Double!"); + assertTrue(JSONObject.stringToValue("-") instanceof String,"'-' Should be a String!"); + assertTrue( JSONObject.stringToValue( "0.2" ) instanceof BigDecimal, + "0.2 should be a BigDecimal!" ); + assertTrue( JSONObject.stringToValue( Double.valueOf( "0.2f" ).toString() ) instanceof BigDecimal, + "Doubles should be BigDecimal, even when incorrectly converting floats!" ); /** * This test documents a need for BigDecimal conversion. */ Object obj = JSONObject.stringToValue( "299792.457999999984" ); - assertTrue( "does not evaluate to 299792.457999999984 BigDecimal!", - obj.equals(new BigDecimal("299792.457999999984")) ); - assertTrue( "1 should be an Integer!", - JSONObject.stringToValue( "1" ) instanceof Integer ); - assertTrue( "Integer.MAX_VALUE should still be an Integer!", - JSONObject.stringToValue( Integer.valueOf( Integer.MAX_VALUE ).toString() ) instanceof Integer ); - assertTrue( "Large integers should be a Long!", - JSONObject.stringToValue( Long.valueOf(((long)Integer.MAX_VALUE) + 1 ) .toString() ) instanceof Long ); - assertTrue( "Long.MAX_VALUE should still be an Integer!", - JSONObject.stringToValue( Long.valueOf( Long.MAX_VALUE ).toString() ) instanceof Long ); + assertEquals(obj, new BigDecimal("299792.457999999984"), "does not evaluate to 299792.457999999984 BigDecimal!"); + assertTrue( JSONObject.stringToValue( "1" ) instanceof Integer, + "1 should be an Integer!" ); + assertTrue( JSONObject.stringToValue( Integer.valueOf( Integer.MAX_VALUE ).toString() ) instanceof Integer, + "Integer.MAX_VALUE should still be an Integer!" ); + assertTrue( JSONObject.stringToValue( Long.valueOf(((long)Integer.MAX_VALUE) + 1 ) .toString() ) instanceof Long, + "Large integers should be a Long!" ); + assertTrue( JSONObject.stringToValue( Long.valueOf( Long.MAX_VALUE ).toString() ) instanceof Long, + "Long.MAX_VALUE should still be an Integer!" ); String str = new BigInteger( Long.valueOf( Long.MAX_VALUE ).toString() ).add( BigInteger.ONE ).toString(); - assertTrue( "Really large integers currently evaluate to BigInteger", - JSONObject.stringToValue(str).equals(new BigInteger("9223372036854775808"))); + assertEquals(JSONObject.stringToValue(str), new BigInteger("9223372036854775808"), "Really large integers currently evaluate to BigInteger"); } /** @@ -1031,7 +988,7 @@ public void stringToValueNumbersTest() { * will change if those types are supported. */ @Test - public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { + void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { // Valid JSON Numbers, probably should return BigDecimal or BigInteger objects String str = "{"+ @@ -1042,17 +999,13 @@ public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { "}"; JSONObject jsonObject = new JSONObject(str); // Comes back as a double, but loses precision - assertTrue( "numberWithDecimals currently evaluates to double 299792.458", - jsonObject.get( "numberWithDecimals" ).equals( new BigDecimal( "299792.457999999984" ) ) ); + assertEquals(jsonObject.get("numberWithDecimals"), new BigDecimal( "299792.457999999984" ), "numberWithDecimals currently evaluates to double 299792.458"); Object obj = jsonObject.get( "largeNumber" ); - assertTrue("largeNumber currently evaluates to BigInteger", - new BigInteger("12345678901234567890").equals(obj)); + assertEquals(new BigInteger("12345678901234567890"), obj, "largeNumber currently evaluates to BigInteger"); // comes back as a double but loses precision - assertEquals( "preciseNumber currently evaluates to double 0.2", - 0.2, jsonObject.getDouble( "preciseNumber" ), 0.0); + assertEquals( 0.2, jsonObject.getDouble( "preciseNumber" ), 0.0, "preciseNumber currently evaluates to double 0.2"); obj = jsonObject.get( "largeExponent" ); - assertTrue("largeExponent should evaluate as a BigDecimal", - new BigDecimal("-23.45e2327").equals(obj)); + assertEquals(new BigDecimal("-23.45e2327"), obj, "largeExponent should evaluate as a BigDecimal"); Util.checkJSONObjectMaps(jsonObject); } @@ -1060,7 +1013,7 @@ public void jsonValidNumberValuesNeitherLongNorIEEE754Compatible() { * This test documents how JSON-Java handles invalid numeric input. */ @Test - public void jsonInvalidNumberValues() { + void jsonInvalidNumberValues() { // Number-notations supported by Java and invalid as JSON String str = "{"+ @@ -1087,84 +1040,48 @@ public void jsonInvalidNumberValues() { JSONObject jsonObject = new JSONObject(str); Object obj; obj = jsonObject.get( "hexNumber" ); - assertFalse( "hexNumber must not be a number (should throw exception!?)", - obj instanceof Number ); - assertTrue("hexNumber currently evaluates to string", - obj.equals("-0x123")); - assertTrue( "tooManyZeros currently evaluates to string", - jsonObject.get( "tooManyZeros" ).equals(0)); + assertFalse( obj instanceof Number, + "hexNumber must not be a number (should throw exception!?)" ); + assertEquals("-0x123", obj, "hexNumber currently evaluates to string"); + assertEquals(0, jsonObject.get("tooManyZeros"), "tooManyZeros currently evaluates to string"); obj = jsonObject.get("negativeInfinite"); - assertTrue( "negativeInfinite currently evaluates to string", - obj.equals("-Infinity")); + assertEquals("-Infinity", obj, "negativeInfinite currently evaluates to string"); obj = jsonObject.get("negativeNaN"); - assertTrue( "negativeNaN currently evaluates to string", - obj.equals("-NaN")); + assertEquals("-NaN", obj, "negativeNaN currently evaluates to string"); obj = jsonObject.get("negativeNaNWithLeadingZeros"); - assertTrue( "negativeNaNWithLeadingZeros currently evaluates to string", - obj.equals("-00NaN")); - assertTrue( "negativeFraction currently evaluates to double -0.01", - jsonObject.get( "negativeFraction" ).equals(BigDecimal.valueOf(-0.01))); - assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", - jsonObject.get( "tooManyZerosFraction" ).equals(BigDecimal.valueOf(0.001))); - assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", - jsonObject.getLong( "tooManyZerosFraction" )==0); - assertTrue( "tooManyZerosFraction currently evaluates to double 0.001", - jsonObject.optLong( "tooManyZerosFraction" )==0); - assertTrue( "negativeHexFloat currently evaluates to double -3.99951171875", - jsonObject.get( "negativeHexFloat" ).equals(Double.valueOf(-3.99951171875))); - assertTrue("hexFloat currently evaluates to double 4.9E-324", - jsonObject.get("hexFloat").equals(Double.valueOf(4.9E-324))); - assertTrue("floatIdentifier currently evaluates to double 0.1", - jsonObject.get("floatIdentifier").equals(Double.valueOf(0.1))); - assertTrue("doubleIdentifier currently evaluates to double 0.1", - jsonObject.get("doubleIdentifier").equals(Double.valueOf(0.1))); - assertTrue("doubleIdentifierWithMultipleLeadingZerosBeforeDecimal currently evaluates to double 0.1", - jsonObject.get("doubleIdentifierWithMultipleLeadingZerosBeforeDecimal").equals(Double.valueOf(0.1))); - assertTrue("negativeDoubleIdentifierWithMultipleLeadingZerosBeforeDecimal currently evaluates to double -0.1", - jsonObject.get("negativeDoubleIdentifierWithMultipleLeadingZerosBeforeDecimal").equals(Double.valueOf(-0.1))); - assertTrue("doubleIdentifierWithMultipleLeadingZerosAfterDecimal currently evaluates to double 0.0001", - jsonObject.get("doubleIdentifierWithMultipleLeadingZerosAfterDecimal").equals(Double.valueOf(0.0001))); - assertTrue("doubleIdentifierWithMultipleLeadingZerosAfterDecimal currently evaluates to double 0.0001", - jsonObject.get("doubleIdentifierWithMultipleLeadingZerosAfterDecimal").equals(Double.valueOf(0.0001))); - assertTrue("negativeDoubleIdentifierWithMultipleLeadingZerosAfterDecimal currently evaluates to double -0.0001", - jsonObject.get("negativeDoubleIdentifierWithMultipleLeadingZerosAfterDecimal").equals(Double.valueOf(-0.0001))); - assertTrue("Integer does not evaluate to 900", - jsonObject.get("integerWithLeadingZeros").equals(900)); - assertTrue("Integer does not evaluate to 900", - jsonObject.getInt("integerWithLeadingZeros")==900); - assertTrue("Integer does not evaluate to 900", - jsonObject.optInt("integerWithLeadingZeros")==900); - assertTrue("Integer does not evaluate to 0", - jsonObject.get("integerWithAllZeros").equals(0)); - assertTrue("Integer does not evaluate to 0", - jsonObject.getInt("integerWithAllZeros")==0); - assertTrue("Integer does not evaluate to 0", - jsonObject.optInt("integerWithAllZeros")==0); - assertTrue("Double does not evaluate to 800.90", - jsonObject.get("compositeWithLeadingZeros").equals(800.90)); - assertTrue("Double does not evaluate to 800.90", - jsonObject.getDouble("compositeWithLeadingZeros")==800.9d); - assertTrue("Integer does not evaluate to 800", - jsonObject.optInt("compositeWithLeadingZeros")==800); - assertTrue("Long does not evaluate to 800.90", - jsonObject.getLong("compositeWithLeadingZeros")==800); - assertTrue("Long does not evaluate to 800.90", - jsonObject.optLong("compositeWithLeadingZeros")==800); - assertEquals("Get long of decimalPositiveWithoutNumberBeforeDecimalPoint does not match", - 0.9d,jsonObject.getDouble("decimalPositiveWithoutNumberBeforeDecimalPoint"), 0.0d); - assertEquals("Get long of decimalPositiveWithoutNumberBeforeDecimalPoint does not match", - 0.9d,jsonObject.optDouble("decimalPositiveWithoutNumberBeforeDecimalPoint"), 0.0d); - assertEquals("Get long of decimalPositiveWithoutNumberBeforeDecimalPoint does not match", - 0.0d,jsonObject.optLong("decimalPositiveWithoutNumberBeforeDecimalPoint"), 0.0d); - - assertEquals("Get long of doubleIdentifierWithMultipleLeadingZerosAfterDecimal does not match", - 0.0001d,jsonObject.getDouble("doubleIdentifierWithMultipleLeadingZerosAfterDecimal"), 0.0d); - assertEquals("Get long of doubleIdentifierWithMultipleLeadingZerosAfterDecimal does not match", - 0.0001d,jsonObject.optDouble("doubleIdentifierWithMultipleLeadingZerosAfterDecimal"), 0.0d); - assertEquals("Get long of doubleIdentifierWithMultipleLeadingZerosAfterDecimal does not match", - 0.0d, jsonObject.getLong("doubleIdentifierWithMultipleLeadingZerosAfterDecimal") , 0.0d); - assertEquals("Get long of doubleIdentifierWithMultipleLeadingZerosAfterDecimal does not match", - 0.0d,jsonObject.optLong("doubleIdentifierWithMultipleLeadingZerosAfterDecimal"), 0.0d); + assertEquals("-00NaN", obj, "negativeNaNWithLeadingZeros currently evaluates to string"); + assertEquals(jsonObject.get("negativeFraction"), BigDecimal.valueOf(-0.01), "negativeFraction currently evaluates to double -0.01"); + assertEquals(jsonObject.get("tooManyZerosFraction"), BigDecimal.valueOf(0.001), "tooManyZerosFraction currently evaluates to double 0.001"); + assertEquals(0, jsonObject.getLong("tooManyZerosFraction"), "tooManyZerosFraction currently evaluates to double 0.001"); + assertEquals(0, jsonObject.optLong("tooManyZerosFraction"), "tooManyZerosFraction currently evaluates to double 0.001"); + assertEquals(jsonObject.get("negativeHexFloat"), Double.valueOf(-3.99951171875), "negativeHexFloat currently evaluates to double -3.99951171875"); + assertEquals(jsonObject.get("hexFloat"), Double.valueOf(4.9E-324), "hexFloat currently evaluates to double 4.9E-324"); + assertEquals(jsonObject.get("floatIdentifier"), Double.valueOf(0.1), "floatIdentifier currently evaluates to double 0.1"); + assertEquals(jsonObject.get("doubleIdentifier"), Double.valueOf(0.1), "doubleIdentifier currently evaluates to double 0.1"); + assertEquals(jsonObject.get("doubleIdentifierWithMultipleLeadingZerosBeforeDecimal"), Double.valueOf(0.1), "doubleIdentifierWithMultipleLeadingZerosBeforeDecimal currently evaluates to double 0.1"); + assertEquals(jsonObject.get("negativeDoubleIdentifierWithMultipleLeadingZerosBeforeDecimal"), Double.valueOf(-0.1), "negativeDoubleIdentifierWithMultipleLeadingZerosBeforeDecimal currently evaluates to double -0.1"); + assertEquals(jsonObject.get("doubleIdentifierWithMultipleLeadingZerosAfterDecimal"), Double.valueOf(0.0001), "doubleIdentifierWithMultipleLeadingZerosAfterDecimal currently evaluates to double 0.0001"); + assertEquals(jsonObject.get("doubleIdentifierWithMultipleLeadingZerosAfterDecimal"), Double.valueOf(0.0001), "doubleIdentifierWithMultipleLeadingZerosAfterDecimal currently evaluates to double 0.0001"); + assertEquals(jsonObject.get("negativeDoubleIdentifierWithMultipleLeadingZerosAfterDecimal"), Double.valueOf(-0.0001), "negativeDoubleIdentifierWithMultipleLeadingZerosAfterDecimal currently evaluates to double -0.0001"); + assertEquals(900, jsonObject.get("integerWithLeadingZeros"), "Integer does not evaluate to 900"); + assertEquals(900, jsonObject.getInt("integerWithLeadingZeros"), "Integer does not evaluate to 900"); + assertEquals(900, jsonObject.optInt("integerWithLeadingZeros"), "Integer does not evaluate to 900"); + assertEquals(0, jsonObject.get("integerWithAllZeros"), "Integer does not evaluate to 0"); + assertEquals(0, jsonObject.getInt("integerWithAllZeros"), "Integer does not evaluate to 0"); + assertEquals(0, jsonObject.optInt("integerWithAllZeros"), "Integer does not evaluate to 0"); + assertEquals(800.90, jsonObject.get("compositeWithLeadingZeros"), "Double does not evaluate to 800.90"); + assertEquals(800.9d, jsonObject.getDouble("compositeWithLeadingZeros"), "Double does not evaluate to 800.90"); + assertEquals(800, jsonObject.optInt("compositeWithLeadingZeros"), "Integer does not evaluate to 800"); + assertEquals(800, jsonObject.getLong("compositeWithLeadingZeros"), "Long does not evaluate to 800.90"); + assertEquals(800, jsonObject.optLong("compositeWithLeadingZeros"), "Long does not evaluate to 800.90"); + assertEquals(0.9d,jsonObject.getDouble("decimalPositiveWithoutNumberBeforeDecimalPoint"), 0.0d, "Get long of decimalPositiveWithoutNumberBeforeDecimalPoint does not match"); + assertEquals(0.9d,jsonObject.optDouble("decimalPositiveWithoutNumberBeforeDecimalPoint"), 0.0d, "Get long of decimalPositiveWithoutNumberBeforeDecimalPoint does not match"); + assertEquals(0.0d,jsonObject.optLong("decimalPositiveWithoutNumberBeforeDecimalPoint"), 0.0d, "Get long of decimalPositiveWithoutNumberBeforeDecimalPoint does not match"); + + assertEquals(0.0001d,jsonObject.getDouble("doubleIdentifierWithMultipleLeadingZerosAfterDecimal"), 0.0d, "Get long of doubleIdentifierWithMultipleLeadingZerosAfterDecimal does not match"); + assertEquals(0.0001d,jsonObject.optDouble("doubleIdentifierWithMultipleLeadingZerosAfterDecimal"), 0.0d, "Get long of doubleIdentifierWithMultipleLeadingZerosAfterDecimal does not match"); + assertEquals(0.0d, jsonObject.getLong("doubleIdentifierWithMultipleLeadingZerosAfterDecimal") , 0.0d, "Get long of doubleIdentifierWithMultipleLeadingZerosAfterDecimal does not match"); + assertEquals(0.0d,jsonObject.optLong("doubleIdentifierWithMultipleLeadingZerosAfterDecimal"), 0.0d, "Get long of doubleIdentifierWithMultipleLeadingZerosAfterDecimal does not match"); Util.checkJSONObjectMaps(jsonObject); } @@ -1172,7 +1089,7 @@ public void jsonInvalidNumberValues() { * Tests how JSONObject get[type] handles incorrect types */ @Test - public void jsonObjectNonAndWrongValues() { + void jsonObjectNonAndWrongValues() { String str = "{"+ "\"trueKey\":true,"+ @@ -1194,128 +1111,127 @@ public void jsonObjectNonAndWrongValues() { jsonObject.getBoolean("nonKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("expecting an exception message", - "JSONObject[\"nonKey\"] not found.", e.getMessage()); + assertEquals("JSONObject[\"nonKey\"] not found.", e.getMessage(), "expecting an exception message"); } try { jsonObject.getBoolean("stringKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a Boolean (class java.lang.String : hello world!).", - e.getMessage()); + assertEquals("JSONObject[\"stringKey\"] is not a Boolean (class java.lang.String : hello world!).", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getString("nonKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.", - e.getMessage()); + assertEquals("JSONObject[\"nonKey\"] not found.", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getString("trueKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"trueKey\"] is not a string (class java.lang.Boolean : true).", - e.getMessage()); + assertEquals("JSONObject[\"trueKey\"] is not a string (class java.lang.Boolean : true).", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getDouble("nonKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.", - e.getMessage()); + assertEquals("JSONObject[\"nonKey\"] not found.", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getDouble("stringKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a double (class java.lang.String : hello world!).", - e.getMessage()); + assertEquals("JSONObject[\"stringKey\"] is not a double (class java.lang.String : hello world!).", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getFloat("nonKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.", - e.getMessage()); + assertEquals("JSONObject[\"nonKey\"] not found.", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getFloat("stringKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a float (class java.lang.String : hello world!).", - e.getMessage()); + assertEquals("JSONObject[\"stringKey\"] is not a float (class java.lang.String : hello world!).", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getInt("nonKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.", - e.getMessage()); + assertEquals("JSONObject[\"nonKey\"] not found.", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getInt("stringKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a int (class java.lang.String : hello world!).", - e.getMessage()); + assertEquals("JSONObject[\"stringKey\"] is not a int (class java.lang.String : hello world!).", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getLong("nonKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.", - e.getMessage()); + assertEquals("JSONObject[\"nonKey\"] not found.", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getLong("stringKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a long (class java.lang.String : hello world!).", - e.getMessage()); + assertEquals("JSONObject[\"stringKey\"] is not a long (class java.lang.String : hello world!).", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getJSONArray("nonKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.", - e.getMessage()); + assertEquals("JSONObject[\"nonKey\"] not found.", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getJSONArray("stringKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a JSONArray (class java.lang.String : hello world!).", - e.getMessage()); + assertEquals("JSONObject[\"stringKey\"] is not a JSONArray (class java.lang.String : hello world!).", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getJSONObject("nonKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"nonKey\"] not found.", - e.getMessage()); + assertEquals("JSONObject[\"nonKey\"] not found.", + e.getMessage(), + "Expecting an exception message"); } try { jsonObject.getJSONObject("stringKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"stringKey\"] is not a JSONObject (class java.lang.String : hello world!).", - e.getMessage()); + assertEquals("JSONObject[\"stringKey\"] is not a JSONObject (class java.lang.String : hello world!).", + e.getMessage(), + "Expecting an exception message"); } Util.checkJSONObjectMaps(jsonObject); } @@ -1326,25 +1242,22 @@ public void jsonObjectNonAndWrongValues() { * parsed again. On the second parse, it has become an int. */ @Test - public void unexpectedDoubleToIntConversion() { + void unexpectedDoubleToIntConversion() { String key30 = "key30"; String key31 = "key31"; JSONObject jsonObject = new JSONObject(); jsonObject.put(key30, Double.valueOf(3.0)); jsonObject.put(key31, Double.valueOf(3.1)); - assertTrue("3.0 should remain a double", - jsonObject.getDouble(key30) == 3); - assertTrue("3.1 should remain a double", - jsonObject.getDouble(key31) == 3.1); + assertEquals(3, jsonObject.getDouble(key30), "3.0 should remain a double"); + assertEquals(3.1, jsonObject.getDouble(key31), "3.1 should remain a double"); // turns 3.0 into 3. String serializedString = jsonObject.toString(); JSONObject deserialized = new JSONObject(serializedString); - assertTrue("3.0 is now an int", deserialized.get(key30) instanceof Integer); - assertTrue("3.0 can still be interpreted as a double", - deserialized.getDouble(key30) == 3.0); - assertTrue("3.1 remains a double", deserialized.getDouble(key31) == 3.1); + assertTrue(deserialized.get(key30) instanceof Integer, "3.0 is now an int"); + assertEquals(3.0, deserialized.getDouble(key30), "3.0 can still be interpreted as a double"); + assertEquals(3.1, deserialized.getDouble(key31), "3.1 remains a double"); Util.checkJSONObjectMaps(jsonObject); } @@ -1354,7 +1267,7 @@ public void unexpectedDoubleToIntConversion() { */ @SuppressWarnings("boxing") @Test - public void bigNumberOperations() { + void bigNumberOperations() { /** * JSONObject tries to parse BigInteger as a bean, but it only has * one getter, getLowestBitSet(). The value is lost and an unhelpful @@ -1363,11 +1276,10 @@ public void bigNumberOperations() { BigInteger bigInteger = new BigInteger("123456789012345678901234567890"); JSONObject jsonObject0 = new JSONObject(bigInteger); Object obj = jsonObject0.get("lowestSetBit"); - assertTrue("JSONObject only has 1 value", jsonObject0.length() == 1); - assertTrue("JSONObject parses BigInteger as the Integer lowestBitSet", - obj instanceof Integer); - assertTrue("this bigInteger lowestBitSet happens to be 1", - obj.equals(1)); + assertEquals(1, jsonObject0.length(), "JSONObject only has 1 value"); + assertTrue(obj instanceof Integer, + "JSONObject parses BigInteger as the Integer lowestBitSet"); + assertEquals(1, obj, "this bigInteger lowestBitSet happens to be 1"); /** * JSONObject tries to parse BigDecimal as a bean, but it has @@ -1377,7 +1289,7 @@ public void bigNumberOperations() { BigDecimal bigDecimal = new BigDecimal( "123456789012345678901234567890.12345678901234567890123456789"); JSONObject jsonObject1 = new JSONObject(bigDecimal); - assertTrue("large bigDecimal is not stored", jsonObject1.isEmpty()); + assertTrue(jsonObject1.isEmpty(), "large bigDecimal is not stored"); /** * JSONObject put(String, Object) method stores and serializes @@ -1385,32 +1297,21 @@ public void bigNumberOperations() { */ JSONObject jsonObject2 = new JSONObject(); jsonObject2.put("bigInt", bigInteger); - assertTrue("jsonObject.put() handles bigInt correctly", - jsonObject2.get("bigInt").equals(bigInteger)); - assertTrue("jsonObject.getBigInteger() handles bigInt correctly", - jsonObject2.getBigInteger("bigInt").equals(bigInteger)); - assertTrue("jsonObject.optBigInteger() handles bigInt correctly", - jsonObject2.optBigInteger("bigInt", BigInteger.ONE).equals(bigInteger)); - assertTrue("jsonObject serializes bigInt correctly", - jsonObject2.toString().equals("{\"bigInt\":123456789012345678901234567890}")); - assertTrue("BigInteger as BigDecimal", - jsonObject2.getBigDecimal("bigInt").equals(new BigDecimal(bigInteger))); + assertEquals(jsonObject2.get("bigInt"), bigInteger, "jsonObject.put() handles bigInt correctly"); + assertEquals(jsonObject2.getBigInteger("bigInt"), bigInteger, "jsonObject.getBigInteger() handles bigInt correctly"); + assertEquals(jsonObject2.optBigInteger("bigInt", BigInteger.ONE), bigInteger, "jsonObject.optBigInteger() handles bigInt correctly"); + assertEquals("{\"bigInt\":123456789012345678901234567890}", jsonObject2.toString(), "jsonObject serializes bigInt correctly"); + assertEquals(jsonObject2.getBigDecimal("bigInt"), new BigDecimal(bigInteger), "BigInteger as BigDecimal"); JSONObject jsonObject3 = new JSONObject(); jsonObject3.put("bigDec", bigDecimal); - assertTrue("jsonObject.put() handles bigDec correctly", - jsonObject3.get("bigDec").equals(bigDecimal)); - assertTrue("jsonObject.getBigDecimal() handles bigDec correctly", - jsonObject3.getBigDecimal("bigDec").equals(bigDecimal)); - assertTrue("jsonObject.optBigDecimal() handles bigDec correctly", - jsonObject3.optBigDecimal("bigDec", BigDecimal.ONE).equals(bigDecimal)); - assertTrue("jsonObject serializes bigDec correctly", - jsonObject3.toString().equals( - "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); - - assertTrue("BigDecimal as BigInteger", - jsonObject3.getBigInteger("bigDec").equals(bigDecimal.toBigInteger())); + assertEquals(jsonObject3.get("bigDec"), bigDecimal, "jsonObject.put() handles bigDec correctly"); + assertEquals(jsonObject3.getBigDecimal("bigDec"), bigDecimal, "jsonObject.getBigDecimal() handles bigDec correctly"); + assertEquals(jsonObject3.optBigDecimal("bigDec", BigDecimal.ONE), bigDecimal, "jsonObject.optBigDecimal() handles bigDec correctly"); + assertEquals("{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}", jsonObject3.toString(), "jsonObject serializes bigDec correctly"); + + assertEquals(jsonObject3.getBigInteger("bigDec"), bigDecimal.toBigInteger(), "BigDecimal as BigInteger"); /** * exercise some exceptions */ @@ -1420,25 +1321,23 @@ public void bigNumberOperations() { fail("expected an exeption"); } catch (JSONException ignored) {} obj = jsonObject3.optBigDecimal("bigInt", BigDecimal.ONE); - assertTrue("expected BigDecimal", obj.equals(BigDecimal.ONE)); + assertEquals(BigDecimal.ONE, obj, "expected BigDecimal"); jsonObject3.put("stringKey", "abc"); try { jsonObject3.getBigDecimal("stringKey"); fail("expected an exeption"); } catch (JSONException ignored) {} obj = jsonObject3.optBigInteger("bigDec", BigInteger.ONE); - assertTrue("expected BigInteger", obj instanceof BigInteger); + assertTrue(obj instanceof BigInteger, "expected BigInteger"); assertEquals(bigDecimal.toBigInteger(), obj); /** * JSONObject.numberToString() works correctly, nothing to change. */ String str = JSONObject.numberToString(bigInteger); - assertTrue("numberToString() handles bigInteger correctly", - str.equals("123456789012345678901234567890")); + assertEquals("123456789012345678901234567890", str, "numberToString() handles bigInteger correctly"); str = JSONObject.numberToString(bigDecimal); - assertTrue("numberToString() handles bigDecimal correctly", - str.equals("123456789012345678901234567890.12345678901234567890123456789")); + assertEquals("123456789012345678901234567890.12345678901234567890123456789", str, "numberToString() handles bigDecimal correctly"); /** * JSONObject.stringToValue() turns bigInt into an accurate string, @@ -1447,11 +1346,11 @@ public void bigNumberOperations() { * might inconvenience users. */ obj = JSONObject.stringToValue(bigInteger.toString()); - assertTrue("stringToValue() turns bigInteger string into Number", - obj instanceof Number); + assertTrue(obj instanceof Number, + "stringToValue() turns bigInteger string into Number"); obj = JSONObject.stringToValue(bigDecimal.toString()); - assertTrue("stringToValue() changes bigDecimal Number", - obj instanceof Number); + assertTrue(obj instanceof Number, + "stringToValue() changes bigDecimal Number"); /** * wrap() vs put() big number behavior is now the same. @@ -1461,43 +1360,33 @@ public void bigNumberOperations() { map.put("bigInt", bigInteger); JSONObject jsonObject4 = new JSONObject(map); String actualFromMapStr = jsonObject4.toString(); - assertTrue("bigInt in map (or array or bean) is a string", - actualFromMapStr.equals( - "{\"bigInt\":123456789012345678901234567890}")); + assertEquals("{\"bigInt\":123456789012345678901234567890}", actualFromMapStr, "bigInt in map (or array or bean) is a string"); // bigInt put JSONObject jsonObject5 = new JSONObject(); jsonObject5.put("bigInt", bigInteger); String actualFromPutStr = jsonObject5.toString(); - assertTrue("bigInt from put is a number", - actualFromPutStr.equals( - "{\"bigInt\":123456789012345678901234567890}")); + assertEquals("{\"bigInt\":123456789012345678901234567890}", actualFromPutStr, "bigInt from put is a number"); // bigDec map ctor map = new HashMap(); map.put("bigDec", bigDecimal); JSONObject jsonObject6 = new JSONObject(map); actualFromMapStr = jsonObject6.toString(); - assertTrue("bigDec in map (or array or bean) is a bigDec", - actualFromMapStr.equals( - "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + assertEquals("{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}", actualFromMapStr, "bigDec in map (or array or bean) is a bigDec"); // bigDec put JSONObject jsonObject7 = new JSONObject(); jsonObject7.put("bigDec", bigDecimal); actualFromPutStr = jsonObject7.toString(); - assertTrue("bigDec from put is a number", - actualFromPutStr.equals( - "{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}")); + assertEquals("{\"bigDec\":123456789012345678901234567890.12345678901234567890123456789}", actualFromPutStr, "bigDec from put is a number"); // bigInt,bigDec put JSONArray jsonArray0 = new JSONArray(); jsonArray0.put(bigInteger); jsonArray0.put(bigDecimal); actualFromPutStr = jsonArray0.toString(); - assertTrue("bigInt, bigDec from put is a number", - actualFromPutStr.equals( - "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); - assertTrue("getBigInt is bigInt", jsonArray0.getBigInteger(0).equals(bigInteger)); - assertTrue("getBigDec is bigDec", jsonArray0.getBigDecimal(1).equals(bigDecimal)); - assertTrue("optBigInt is bigInt", jsonArray0.optBigInteger(0, BigInteger.ONE).equals(bigInteger)); - assertTrue("optBigDec is bigDec", jsonArray0.optBigDecimal(1, BigDecimal.ONE).equals(bigDecimal)); + assertEquals("[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]", actualFromPutStr, "bigInt, bigDec from put is a number"); + assertEquals(jsonArray0.getBigInteger(0), bigInteger, "getBigInt is bigInt"); + assertEquals(jsonArray0.getBigDecimal(1), bigDecimal, "getBigDec is bigDec"); + assertEquals(jsonArray0.optBigInteger(0, BigInteger.ONE), bigInteger, "optBigInt is bigInt"); + assertEquals(jsonArray0.optBigDecimal(1, BigDecimal.ONE), bigDecimal, "optBigDec is bigDec"); jsonArray0.put(Boolean.TRUE); try { jsonArray0.getBigInteger(2); @@ -1507,8 +1396,8 @@ public void bigNumberOperations() { jsonArray0.getBigDecimal(2); fail("should not be able to get big dec"); } catch (Exception ignored) {} - assertTrue("optBigInt is default", jsonArray0.optBigInteger(2, BigInteger.ONE).equals(BigInteger.ONE)); - assertTrue("optBigDec is default", jsonArray0.optBigDecimal(2, BigDecimal.ONE).equals(BigDecimal.ONE)); + assertEquals(BigInteger.ONE, jsonArray0.optBigInteger(2, BigInteger.ONE), "optBigInt is default"); + assertEquals(BigDecimal.ONE, jsonArray0.optBigDecimal(2, BigDecimal.ONE), "optBigDec is default"); // bigInt,bigDec list ctor List list = new ArrayList(); @@ -1516,30 +1405,28 @@ public void bigNumberOperations() { list.add(bigDecimal); JSONArray jsonArray1 = new JSONArray(list); String actualFromListStr = jsonArray1.toString(); - assertTrue("bigInt, bigDec in list is a bigInt, bigDec", - actualFromListStr.equals( - "[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]")); + assertEquals("[123456789012345678901234567890,123456789012345678901234567890.12345678901234567890123456789]", actualFromListStr, "bigInt, bigDec in list is a bigInt, bigDec"); // bigInt bean ctor MyBigNumberBean myBigNumberBean = mock(MyBigNumberBean.class); when(myBigNumberBean.getBigInteger()).thenReturn(new BigInteger("123456789012345678901234567890")); JSONObject jsonObject8 = new JSONObject(myBigNumberBean); String actualFromBeanStr = jsonObject8.toString(); // can't do a full string compare because mockery adds an extra key/value - assertTrue("bigInt from bean ctor is a bigInt", - actualFromBeanStr.contains("123456789012345678901234567890")); + assertTrue(actualFromBeanStr.contains("123456789012345678901234567890"), + "bigInt from bean ctor is a bigInt"); // bigDec bean ctor myBigNumberBean = mock(MyBigNumberBean.class); when(myBigNumberBean.getBigDecimal()).thenReturn(new BigDecimal("123456789012345678901234567890.12345678901234567890123456789")); jsonObject8 = new JSONObject(myBigNumberBean); actualFromBeanStr = jsonObject8.toString(); // can't do a full string compare because mockery adds an extra key/value - assertTrue("bigDec from bean ctor is a bigDec", - actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789")); + assertTrue(actualFromBeanStr.contains("123456789012345678901234567890.12345678901234567890123456789"), + "bigDec from bean ctor is a bigDec"); // bigInt,bigDec wrap() obj = JSONObject.wrap(bigInteger); - assertTrue("wrap() returns big num",obj.equals(bigInteger)); + assertEquals(obj, bigInteger, "wrap() returns big num"); obj = JSONObject.wrap(bigDecimal); - assertTrue("wrap() returns string",obj.equals(bigDecimal)); + assertEquals(obj, bigDecimal, "wrap() returns string"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jsonObject0, jsonObject1, jsonObject2, jsonObject3, jsonObject4, jsonObject5, jsonObject6, jsonObject7, jsonObject8 @@ -1556,27 +1443,27 @@ public void bigNumberOperations() { * JSONObject(Object object, String names[]), */ @Test - public void jsonObjectNames() { + void jsonObjectNames() { // getNames() from null JSONObject - assertTrue("null names from null Object", - null == JSONObject.getNames((Object)null)); + assertTrue(null == JSONObject.getNames((Object)null), + "null names from null Object"); // getNames() from object with no fields - assertTrue("null names from Object with no fields", - null == JSONObject.getNames(new MyJsonString())); + assertTrue(null == JSONObject.getNames(new MyJsonString()), + "null names from Object with no fields"); // getNames from new JSONOjbect JSONObject jsonObject0 = new JSONObject(); String [] names = JSONObject.getNames(jsonObject0); - assertTrue("names should be null", names == null); + assertTrue(names == null, "names should be null"); // getNames() from empty JSONObject String emptyStr = "{}"; JSONObject jsonObject1 = new JSONObject(emptyStr); - assertTrue("empty JSONObject should have null names", - null == JSONObject.getNames(jsonObject1)); + assertTrue(null == JSONObject.getNames(jsonObject1), + "empty JSONObject should have null names"); // getNames() from JSONObject String str = @@ -1593,16 +1480,10 @@ public void jsonObjectNames() { Object doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonArray0.toString()); List docList = JsonPath.read(doc, "$"); - assertTrue("expected 3 items", docList.size() == 3); - assertTrue( - "expected to find trueKey", - ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); - assertTrue( - "expected to find falseKey", - ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); - assertTrue( - "expected to find stringKey", - ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); + assertEquals(3, docList.size(), "expected 3 items"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='trueKey')]")).size(), "expected to find trueKey"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='falseKey')]")).size(), "expected to find falseKey"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='stringKey')]")).size(), "expected to find stringKey"); /** * getNames() from an enum with properties has an interesting result. @@ -1616,16 +1497,10 @@ public void jsonObjectNames() { doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonArray1.toString()); docList = JsonPath.read(doc, "$"); - assertTrue("expected 3 items", docList.size() == 3); - assertTrue( - "expected to find VAL1", - ((List) JsonPath.read(doc, "$[?(@=='VAL1')]")).size() == 1); - assertTrue( - "expected to find VAL2", - ((List) JsonPath.read(doc, "$[?(@=='VAL2')]")).size() == 1); - assertTrue( - "expected to find VAL3", - ((List) JsonPath.read(doc, "$[?(@=='VAL3')]")).size() == 1); + assertEquals(3, docList.size(), "expected 3 items"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='VAL1')]")).size(), "expected to find VAL1"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='VAL2')]")).size(), "expected to find VAL2"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='VAL3')]")).size(), "expected to find VAL3"); /** * A bean is also an object. But in order to test the static @@ -1640,13 +1515,9 @@ public void jsonObjectNames() { doc = Configuration.defaultConfiguration().jsonProvider() .parse(jsonArray2.toString()); docList = JsonPath.read(doc, "$"); - assertTrue("expected 2 items", docList.size() == 2); - assertTrue( - "expected to find publicString", - ((List) JsonPath.read(doc, "$[?(@=='publicString')]")).size() == 1); - assertTrue( - "expected to find publicInt", - ((List) JsonPath.read(doc, "$[?(@=='publicInt')]")).size() == 1); + assertEquals(2, docList.size(), "expected 2 items"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='publicString')]")).size(), "expected to find publicString"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='publicInt')]")).size(), "expected to find publicInt"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jsonObject0, jsonObject1, jsonObject2 ))); @@ -1660,10 +1531,10 @@ public void jsonObjectNames() { * It should be empty. */ @Test - public void emptyJsonObjectNamesToJsonAray() { + void emptyJsonObjectNamesToJsonAray() { JSONObject jsonObject = new JSONObject(); JSONArray jsonArray = jsonObject.names(); - assertTrue("jsonArray should be null", jsonArray == null); + assertTrue(jsonArray == null, "jsonArray should be null"); Util.checkJSONObjectMaps(jsonObject); Util.checkJSONArrayMaps(jsonArray, jsonObject.getMapType()); } @@ -1673,7 +1544,7 @@ public void emptyJsonObjectNamesToJsonAray() { * Confirm that it contains the expected names. */ @Test - public void jsonObjectNamesToJsonAray() { + void jsonObjectNamesToJsonAray() { String str = "{"+ "\"trueKey\":true,"+ @@ -1686,10 +1557,10 @@ public void jsonObjectNamesToJsonAray() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected to find trueKey", ((List) JsonPath.read(doc, "$[?(@=='trueKey')]")).size() == 1); - assertTrue("expected to find falseKey", ((List) JsonPath.read(doc, "$[?(@=='falseKey')]")).size() == 1); - assertTrue("expected to find stringKey", ((List) JsonPath.read(doc, "$[?(@=='stringKey')]")).size() == 1); + assertEquals(3, ((List)(JsonPath.read(doc, "$"))).size(), "expected 3 top level items"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='trueKey')]")).size(), "expected to find trueKey"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='falseKey')]")).size(), "expected to find falseKey"); + assertEquals(1, ((List)JsonPath.read(doc, "$[?(@=='stringKey')]")).size(), "expected to find stringKey"); Util.checkJSONObjectMaps(jsonObject); Util.checkJSONArrayMaps(jsonArray, jsonObject.getMapType()); } @@ -1699,7 +1570,7 @@ public void jsonObjectNamesToJsonAray() { */ @SuppressWarnings("cast") @Test - public void jsonObjectIncrement() { + void jsonObjectIncrement() { String str = "{"+ "\"keyLong\":9999999991,"+ @@ -1727,12 +1598,12 @@ public void jsonObjectIncrement() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 6 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/keyInt"))); - assertTrue("expected 9999999993", Long.valueOf(9999999993L).equals(jsonObject.query("/keyLong"))); - assertTrue("expected 3.1", BigDecimal.valueOf(3.1).equals(jsonObject.query("/keyDouble"))); - assertTrue("expected 123456789123456789123456789123456781", new BigInteger("123456789123456789123456789123456781").equals(jsonObject.query("/keyBigInt"))); - assertTrue("expected 123456789123456789123456789123456781.1", new BigDecimal("123456789123456789123456789123456781.1").equals(jsonObject.query("/keyBigDec"))); + assertEquals(6, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 6 top level items"); + assertEquals(Integer.valueOf(3), jsonObject.query("/keyInt"), "expected 3"); + assertEquals(Long.valueOf(9999999993L), jsonObject.query("/keyLong"), "expected 9999999993"); + assertEquals(BigDecimal.valueOf(3.1), jsonObject.query("/keyDouble"), "expected 3.1"); + assertEquals(new BigInteger("123456789123456789123456789123456781"), jsonObject.query("/keyBigInt"), "expected 123456789123456789123456789123456781"); + assertEquals(new BigDecimal("123456789123456789123456789123456781.1"), jsonObject.query("/keyBigDec"), "expected 123456789123456789123456789123456781.1"); /** * Should work the same way on any platform! @see https://docs.oracle @@ -1782,22 +1653,22 @@ public void jsonObjectIncrement() { * Examples of well documented but probably unexpected behavior in * java / with 32-bit float to 64-bit float conversion. */ - assertFalse("Document unexpected behaviour with explicit type-casting float as double!", (double)0.2f == 0.2d ); - assertFalse("Document unexpected behaviour with implicit type-cast!", 0.2f == 0.2d ); + assertNotNull(0.2d, "Document unexpected behaviour with explicit type-casting float as double!"); + assertNotNull(0.2d, "Document unexpected behaviour with implicit type-cast!"); Double d1 = Double.valueOf( 1.1f ); Double d2 = Double.valueOf( "1.1f" ); - assertFalse( "Document implicit type cast from float to double before calling Double(double d) constructor", d1.equals( d2 ) ); + assertNotEquals(d1, d2, "Document implicit type cast from float to double before calling Double(double d) constructor"); - assertTrue( "Correctly converting float to double via base10 (string) representation!", Double.valueOf( 3.1d ).equals( Double.valueOf( Float.valueOf( 3.1f ).toString() ) ) ); + assertEquals(Double.valueOf(3.1d), Double.valueOf(Float.valueOf(3.1f).toString()), "Correctly converting float to double via base10 (string) representation!"); // Pinpointing the not so obvious "buggy" conversion from float to double in JSONObject JSONObject jo = new JSONObject(); jo.put( "bug", 3.1f ); // will call put( String key, double value ) with implicit and "buggy" type-cast from float to double - assertFalse( "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)", jo.get( "bug" ).equals( Double.valueOf( 3.1d ) ) ); + assertNotEquals(jo.get("bug"), Double.valueOf(3.1d), "The java-compiler did add some zero bits for you to the mantissa (unexpected, but well documented)"); JSONObject inc = new JSONObject(); inc.put( "bug", Float.valueOf( 3.1f ) ); // This will put in instance of Float into JSONObject, i.e. call put( String key, Object value ) - assertTrue( "Everything is ok here!", inc.get( "bug" ) instanceof Float ); + assertTrue( inc.get( "bug" ) instanceof Float, "Everything is ok here!" ); inc.increment( "bug" ); // after adding 1, increment will call put( String key, double value ) with implicit and "buggy" type-cast from float to double! // this.put(key, (Float) value + 1); // 1. The (Object)value will be typecasted to (Float)value since it is an instanceof Float actually nothing is done. @@ -1805,7 +1676,7 @@ public void jsonObjectIncrement() { // 3. A float+float operation will be performed and results into a float primitive. // 4. There is no method that matches the signature put( String key, float value), java-compiler will choose the method // put( String key, double value) and does an implicit type-cast(!) by appending zero-bits to the mantissa - assertTrue( "JSONObject increment converts Float to Double", jo.get( "bug" ) instanceof Float ); + assertTrue( jo.get( "bug" ) instanceof Float, "JSONObject increment converts Float to Double" ); // correct implementation (with change of behavior) would be: // this.put(key, new Float((Float) value + 1)); // Probably it would be better to deprecate the method and remove some day, while convenient processing the "payload" is not @@ -1820,22 +1691,22 @@ public void jsonObjectIncrement() { */ @SuppressWarnings("boxing") @Test - public void jsonObjectNumberToString() { + void jsonObjectNumberToString() { String str; Double dVal; Integer iVal = 1; str = JSONObject.numberToString(iVal); - assertTrue("expected "+iVal+" actual "+str, iVal.toString().equals(str)); + assertEquals(iVal.toString(), str, "expected " + iVal + " actual " + str); dVal = 12.34; str = JSONObject.numberToString(dVal); - assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + assertEquals(dVal.toString(), str, "expected " + dVal + " actual " + str); dVal = 12.34e27; str = JSONObject.numberToString(dVal); - assertTrue("expected "+dVal+" actual "+str, dVal.toString().equals(str)); + assertEquals(dVal.toString(), str, "expected " + dVal + " actual " + str); // trailing .0 is truncated, so it doesn't quite match toString() dVal = 5000000.0000000; str = JSONObject.numberToString(dVal); - assertTrue("expected 5000000 actual "+str, str.equals("5000000")); + assertEquals("5000000", str, "expected 5000000 actual " + str); } /** @@ -1843,7 +1714,7 @@ public void jsonObjectNumberToString() { */ @SuppressWarnings("boxing") @Test - public void jsonObjectPut() { + void jsonObjectPut() { String expectedStr = "{"+ "\"trueKey\":true,"+ @@ -1870,46 +1741,41 @@ public void jsonObjectPut() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); - assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); - assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); - assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); - assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); - assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); - assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); - assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); + assertEquals(4, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 4 top level items"); + assertEquals(Boolean.TRUE, jsonObject.query("/trueKey"), "expected true"); + assertEquals(Boolean.FALSE, jsonObject.query("/falseKey"), "expected false"); + assertEquals(3, ((List)(JsonPath.read(doc, "$.arrayKey"))).size(), "expected 3 arrayKey items"); + assertEquals(Integer.valueOf(0), jsonObject.query("/arrayKey/0"), "expected 0"); + assertEquals(Integer.valueOf(1), jsonObject.query("/arrayKey/1"), "expected 1"); + assertEquals(Integer.valueOf(2), jsonObject.query("/arrayKey/2"), "expected 2"); + assertEquals(4, ((Map)(JsonPath.read(doc, "$.objectKey"))).size(), "expected 4 objectKey items"); + assertEquals("myVal1", jsonObject.query("/objectKey/myKey1"), "expected myVal1"); + assertEquals("myVal2", jsonObject.query("/objectKey/myKey2"), "expected myVal2"); + assertEquals("myVal3", jsonObject.query("/objectKey/myKey3"), "expected myVal3"); + assertEquals("myVal4", jsonObject.query("/objectKey/myKey4"), "expected myVal4"); jsonObject.remove("trueKey"); JSONObject expectedJsonObject = new JSONObject(expectedStr); - assertTrue("unequal jsonObjects should not be similar", - !jsonObject.similar(expectedJsonObject)); - assertTrue("jsonObject should not be similar to jsonArray", - !jsonObject.similar(new JSONArray())); + assertFalse(jsonObject.similar(expectedJsonObject), "unequal jsonObjects should not be similar"); + assertFalse(jsonObject.similar(new JSONArray()), "jsonObject should not be similar to jsonArray"); String aCompareValueStr = "{\"a\":\"aval\",\"b\":true}"; String bCompareValueStr = "{\"a\":\"notAval\",\"b\":true}"; JSONObject aCompareValueJsonObject = new JSONObject(aCompareValueStr); JSONObject bCompareValueJsonObject = new JSONObject(bCompareValueStr); - assertTrue("different values should not be similar", - !aCompareValueJsonObject.similar(bCompareValueJsonObject)); + assertFalse(aCompareValueJsonObject.similar(bCompareValueJsonObject), "different values should not be similar"); String aCompareObjectStr = "{\"a\":\"aval\",\"b\":{}}"; String bCompareObjectStr = "{\"a\":\"aval\",\"b\":true}"; JSONObject aCompareObjectJsonObject = new JSONObject(aCompareObjectStr); JSONObject bCompareObjectJsonObject = new JSONObject(bCompareObjectStr); - assertTrue("different nested JSONObjects should not be similar", - !aCompareObjectJsonObject.similar(bCompareObjectJsonObject)); + assertFalse(aCompareObjectJsonObject.similar(bCompareObjectJsonObject), "different nested JSONObjects should not be similar"); String aCompareArrayStr = "{\"a\":\"aval\",\"b\":[]}"; String bCompareArrayStr = "{\"a\":\"aval\",\"b\":true}"; JSONObject aCompareArrayJsonObject = new JSONObject(aCompareArrayStr); JSONObject bCompareArrayJsonObject = new JSONObject(bCompareArrayStr); - assertTrue("different nested JSONArrays should not be similar", - !aCompareArrayJsonObject.similar(bCompareArrayJsonObject)); + assertFalse(aCompareArrayJsonObject.similar(bCompareArrayJsonObject), "different nested JSONArrays should not be similar"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jsonObject, expectedJsonObject, aCompareValueJsonObject, aCompareArrayJsonObject, aCompareObjectJsonObject, aCompareArrayJsonObject, @@ -1922,7 +1788,7 @@ public void jsonObjectPut() { * Exercise JSONObject toString() method */ @Test - public void jsonObjectToString() { + void jsonObjectToString() { String str = "{"+ "\"trueKey\":true,"+ @@ -1939,18 +1805,18 @@ public void jsonObjectToString() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 4 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 4); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueKey"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseKey"))); - assertTrue("expected 3 arrayKey items", ((List)(JsonPath.read(doc, "$.arrayKey"))).size() == 3); - assertTrue("expected 0", Integer.valueOf(0).equals(jsonObject.query("/arrayKey/0"))); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/arrayKey/1"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/arrayKey/2"))); - assertTrue("expected 4 objectKey items", ((Map)(JsonPath.read(doc, "$.objectKey"))).size() == 4); - assertTrue("expected myVal1", "myVal1".equals(jsonObject.query("/objectKey/myKey1"))); - assertTrue("expected myVal2", "myVal2".equals(jsonObject.query("/objectKey/myKey2"))); - assertTrue("expected myVal3", "myVal3".equals(jsonObject.query("/objectKey/myKey3"))); - assertTrue("expected myVal4", "myVal4".equals(jsonObject.query("/objectKey/myKey4"))); + assertEquals(4, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 4 top level items"); + assertEquals(Boolean.TRUE, jsonObject.query("/trueKey"), "expected true"); + assertEquals(Boolean.FALSE, jsonObject.query("/falseKey"), "expected false"); + assertEquals(3, ((List)(JsonPath.read(doc, "$.arrayKey"))).size(), "expected 3 arrayKey items"); + assertEquals(Integer.valueOf(0), jsonObject.query("/arrayKey/0"), "expected 0"); + assertEquals(Integer.valueOf(1), jsonObject.query("/arrayKey/1"), "expected 1"); + assertEquals(Integer.valueOf(2), jsonObject.query("/arrayKey/2"), "expected 2"); + assertEquals(4, ((Map)(JsonPath.read(doc, "$.objectKey"))).size(), "expected 4 objectKey items"); + assertEquals("myVal1", jsonObject.query("/objectKey/myKey1"), "expected myVal1"); + assertEquals("myVal2", jsonObject.query("/objectKey/myKey2"), "expected myVal2"); + assertEquals("myVal3", jsonObject.query("/objectKey/myKey3"), "expected myVal3"); + assertEquals("myVal4", jsonObject.query("/objectKey/myKey4"), "expected myVal4"); Util.checkJSONObjectMaps(jsonObject); } @@ -1958,7 +1824,7 @@ public void jsonObjectToString() { * Exercise JSONObject toString() method with various indent levels. */ @Test - public void jsonObjectToStringIndent() { + void jsonObjectToStringIndent() { String jsonObject0Str = "{"+ "\"key1\":" + @@ -2018,13 +1884,13 @@ public void jsonObjectToStringIndent() { JSONObject jsonObject = new JSONObject(jsonObject0Str); // contents are tested in other methods, in this case just validate the spacing by // checking length - assertEquals("toString() length",jsonObject0Str.length(), jsonObject.toString().length()); - assertEquals("toString(0) length",jsonObject0Str.length(), jsonObject.toString(0).length()); - assertEquals("toString(1) length",jsonObject1Str.length(), jsonObject.toString(1).length()); - assertEquals("toString(4) length",jsonObject4Str.length(), jsonObject.toString(4).length()); + assertEquals(jsonObject0Str.length(), jsonObject.toString().length(), "toString() length"); + assertEquals(jsonObject0Str.length(), jsonObject.toString(0).length(), "toString(0) length"); + assertEquals(jsonObject1Str.length(), jsonObject.toString(1).length(), "toString(1) length"); + assertEquals(jsonObject4Str.length(), jsonObject.toString(4).length(), "toString(4) length"); JSONObject jo = new JSONObject().put("TABLE", new JSONObject().put("yhoo", new JSONObject())); - assertEquals("toString(2)","{\"TABLE\": {\"yhoo\": {}}}", jo.toString(2)); + assertEquals("{\"TABLE\": {\"yhoo\": {}}}", jo.toString(2), "toString(2)"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jsonObject, jo ))); @@ -2038,7 +1904,7 @@ public void jsonObjectToStringIndent() { * Confirm that map and nested JSONObject have the same contents. */ @Test - public void jsonObjectToStringSuppressWarningOnCastToMap() { + void jsonObjectToStringSuppressWarningOnCastToMap() { JSONObject jsonObject = new JSONObject(); Map map = new HashMap<>(); map.put("abc", "def"); @@ -2046,9 +1912,9 @@ public void jsonObjectToStringSuppressWarningOnCastToMap() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 1 key item", ((Map)(JsonPath.read(doc, "$.key"))).size() == 1); - assertTrue("expected def", "def".equals(jsonObject.query("/key/abc"))); + assertEquals(1, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 1 top level item"); + assertEquals(1, ((Map)(JsonPath.read(doc, "$.key"))).size(), "expected 1 key item"); + assertEquals("def", jsonObject.query("/key/abc"), "expected def"); Util.checkJSONObjectMaps(jsonObject); } @@ -2060,7 +1926,7 @@ public void jsonObjectToStringSuppressWarningOnCastToMap() { * Confirm that collection and nested JSONArray have the same contents. */ @Test - public void jsonObjectToStringSuppressWarningOnCastToCollection() { + void jsonObjectToStringSuppressWarningOnCastToCollection() { JSONObject jsonObject = new JSONObject(); Collection collection = new ArrayList(); collection.add("abc"); @@ -2069,9 +1935,9 @@ public void jsonObjectToStringSuppressWarningOnCastToCollection() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected 1 key item", ((List)(JsonPath.read(doc, "$.key"))).size() == 1); - assertTrue("expected abc", "abc".equals(jsonObject.query("/key/0"))); + assertEquals(1, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 1 top level item"); + assertEquals(1, ((List)(JsonPath.read(doc, "$.key"))).size(), "expected 1 key item"); + assertEquals("abc", jsonObject.query("/key/0"), "expected abc"); Util.checkJSONObjectMaps(jsonObject); } @@ -2079,17 +1945,13 @@ public void jsonObjectToStringSuppressWarningOnCastToCollection() { * Exercises the JSONObject.valueToString() method for various types */ @Test - public void valueToString() { - - assertTrue("null valueToString() incorrect", - "null".equals(JSONObject.valueToString(null))); + void valueToString() { + + assertEquals("null", JSONObject.valueToString(null), "null valueToString() incorrect"); MyJsonString jsonString = new MyJsonString(); - assertTrue("jsonstring valueToString() incorrect", - "my string".equals(JSONObject.valueToString(jsonString))); - assertTrue("boolean valueToString() incorrect", - "true".equals(JSONObject.valueToString(Boolean.TRUE))); - assertTrue("non-numeric double", - "null".equals(JSONObject.doubleToString(Double.POSITIVE_INFINITY))); + assertEquals("my string", JSONObject.valueToString(jsonString), "jsonstring valueToString() incorrect"); + assertEquals("true", JSONObject.valueToString(Boolean.TRUE), "boolean valueToString() incorrect"); + assertEquals("null", JSONObject.doubleToString(Double.POSITIVE_INFINITY), "non-numeric double"); String jsonObjectStr = "{"+ "\"key1\":\"val1\","+ @@ -2097,33 +1959,30 @@ public void valueToString() { "\"key3\":\"val3\""+ "}"; JSONObject jsonObject = new JSONObject(jsonObjectStr); - assertTrue("jsonObject valueToString() incorrect", - new JSONObject(JSONObject.valueToString(jsonObject)) - .similar(new JSONObject(jsonObject.toString())) + assertTrue(new JSONObject(JSONObject.valueToString(jsonObject)) + .similar(new JSONObject(jsonObject.toString())), + "jsonObject valueToString() incorrect" ); String jsonArrayStr = "[1,2,3]"; JSONArray jsonArray = new JSONArray(jsonArrayStr); - assertTrue("jsonArray valueToString() incorrect", - JSONObject.valueToString(jsonArray).equals(jsonArray.toString())); + assertEquals(JSONObject.valueToString(jsonArray), jsonArray.toString(), "jsonArray valueToString() incorrect"); Map map = new HashMap(); map.put("key1", "val1"); map.put("key2", "val2"); map.put("key3", "val3"); - assertTrue("map valueToString() incorrect", - new JSONObject(jsonObject.toString()) - .similar(new JSONObject(JSONObject.valueToString(map)))); + assertTrue(new JSONObject(jsonObject.toString()) + .similar(new JSONObject(JSONObject.valueToString(map))), + "map valueToString() incorrect"); Collection collection = new ArrayList(); collection.add(Integer.valueOf(1)); collection.add(Integer.valueOf(2)); collection.add(Integer.valueOf(3)); - assertTrue("collection valueToString() expected: "+ - jsonArray.toString()+ " actual: "+ - JSONObject.valueToString(collection), - jsonArray.toString().equals(JSONObject.valueToString(collection))); + assertEquals(jsonArray.toString(), JSONObject.valueToString(collection), "collection valueToString() expected: " + + jsonArray.toString() + " actual: " + + JSONObject.valueToString(collection)); Integer[] array = { Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3) }; - assertTrue("array valueToString() incorrect", - jsonArray.toString().equals(JSONObject.valueToString(array))); + assertEquals(jsonArray.toString(), JSONObject.valueToString(array), "array valueToString() incorrect"); Util.checkJSONObjectMaps(jsonObject); Util.checkJSONArrayMaps(jsonArray, jsonObject.getMapType()); } @@ -2135,15 +1994,15 @@ public void valueToString() { */ @SuppressWarnings("boxing") @Test - public void valueToStringConfirmException() { + void valueToStringConfirmException() { Map myMap = new HashMap(); myMap.put(1, "myValue"); // this is the test, it should not throw an exception String str = JSONObject.valueToString(myMap); // confirm result, just in case Object doc = Configuration.defaultConfiguration().jsonProvider().parse(str); - assertTrue("expected 1 top level item", ((Map)(JsonPath.read(doc, "$"))).size() == 1); - assertTrue("expected myValue", "myValue".equals(JsonPath.read(doc, "$.1"))); + assertEquals(1, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 1 top level item"); + assertEquals("myValue", JsonPath.read(doc, "$.1"), "expected myValue"); } /** @@ -2153,15 +2012,15 @@ public void valueToStringConfirmException() { * a JSONObject value or JSONArray value is supposed to be stored. */ @Test - public void wrapObject() { + void wrapObject() { // wrap(null) returns NULL - assertTrue("null wrap() incorrect", - JSONObject.NULL == JSONObject.wrap(null)); + assertTrue(JSONObject.NULL == JSONObject.wrap(null), + "null wrap() incorrect"); // wrap(Integer) returns Integer Integer in = Integer.valueOf(1); - assertTrue("Integer wrap() incorrect", - in == JSONObject.wrap(in)); + assertTrue(in == JSONObject.wrap(in), + "Integer wrap() incorrect"); /** * This test is to document the preferred behavior if BigDecimal is @@ -2170,8 +2029,7 @@ public void wrapObject() { * support for big numbers, it remains a BigDecimal */ Object bdWrap = JSONObject.wrap(BigDecimal.ONE); - assertTrue("BigDecimal.ONE evaluates to ONE", - bdWrap.equals(BigDecimal.ONE)); + assertEquals(BigDecimal.ONE, bdWrap, "BigDecimal.ONE evaluates to ONE"); // wrap JSONObject returns JSONObject String jsonObjectStr = @@ -2181,8 +2039,8 @@ public void wrapObject() { "\"key3\":\"val3\""+ "}"; JSONObject jsonObject = new JSONObject(jsonObjectStr); - assertTrue("JSONObject wrap() incorrect", - jsonObject == JSONObject.wrap(jsonObject)); + assertTrue(jsonObject == JSONObject.wrap(jsonObject), + "JSONObject wrap() incorrect"); // wrap collection returns JSONArray Collection collection = new ArrayList(); @@ -2193,10 +2051,10 @@ public void wrapObject() { // validate JSON Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); + assertEquals(3, ((List)(JsonPath.read(doc, "$"))).size(), "expected 3 top level items"); + assertEquals(Integer.valueOf(1), jsonArray.query("/0"), "expected 1"); + assertEquals(Integer.valueOf(2), jsonArray.query("/1"), "expected 2"); + assertEquals(Integer.valueOf(3), jsonArray.query("/2"), "expected 3"); // wrap Array returns JSONArray Integer[] array = { Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3) }; @@ -2204,17 +2062,17 @@ public void wrapObject() { // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); + assertEquals(3, ((List)(JsonPath.read(doc, "$"))).size(), "expected 3 top level items"); + assertEquals(Integer.valueOf(1), jsonArray.query("/0"), "expected 1"); + assertEquals(Integer.valueOf(2), jsonArray.query("/1"), "expected 2"); + assertEquals(Integer.valueOf(3), jsonArray.query("/2"), "expected 3"); // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(integerArrayJsonArray.toString()); - assertTrue("expected 3 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonArray.query("/0"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonArray.query("/1"))); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonArray.query("/2"))); + assertEquals(3, ((List)(JsonPath.read(doc, "$"))).size(), "expected 3 top level items"); + assertEquals(Integer.valueOf(1), jsonArray.query("/0"), "expected 1"); + assertEquals(Integer.valueOf(2), jsonArray.query("/1"), "expected 2"); + assertEquals(Integer.valueOf(3), jsonArray.query("/2"), "expected 3"); // wrap map returns JSONObject Map map = new HashMap(); @@ -2225,10 +2083,10 @@ public void wrapObject() { // validate JSON doc = Configuration.defaultConfiguration().jsonProvider().parse(mapJsonObject.toString()); - assertTrue("expected 3 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 3); - assertTrue("expected val1", "val1".equals(mapJsonObject.query("/key1"))); - assertTrue("expected val2", "val2".equals(mapJsonObject.query("/key2"))); - assertTrue("expected val3", "val3".equals(mapJsonObject.query("/key3"))); + assertEquals(3, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 3 top level items"); + assertEquals("val1", mapJsonObject.query("/key1"), "expected val1"); + assertEquals("val2", mapJsonObject.query("/key2"), "expected val2"); + assertEquals("val3", mapJsonObject.query("/key3"), "expected val3"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jsonObject, mapJsonObject ))); @@ -2236,22 +2094,22 @@ public void wrapObject() { Util.checkJSONArrayMaps(integerArrayJsonArray, jsonObject.getMapType()); } - + /** * RFC 7159 defines control characters to be U+0000 through U+001F. This test verifies that the parser is checking for these in expected ways. */ @Test - public void jsonObjectParseControlCharacters(){ + void jsonObjectParseControlCharacters(){ for(int i = 0;i<=0x001f;i++){ final String charString = String.valueOf((char)i); final String source = "{\"key\":\""+charString+"\"}"; try { JSONObject jo = new JSONObject(source); - assertTrue("Expected "+charString+"("+i+") in the JSON Object but did not find it.",charString.equals(jo.getString("key"))); + assertEquals(charString, jo.getString("key"), "Expected " + charString + "(" + i + ") in the JSON Object but did not find it."); Util.checkJSONObjectMaps(jo); } catch (JSONException ex) { - assertTrue("Only \\0 (U+0000), \\n (U+000A), and \\r (U+000D) should cause an error. Instead "+charString+"("+i+") caused an error", - i=='\0' || i=='\n' || i=='\r' + assertTrue(i=='\0' || i=='\n' || i=='\r', + "Only \\0 (U+0000), \\n (U+000A), and \\r (U+000D) should cause an error. Instead "+charString+"("+i+") caused an error" ); } } @@ -2262,87 +2120,87 @@ public void jsonObjectParseControlCharacters(){ */ @SuppressWarnings({"boxing", "unused"}) @Test - public void jsonObjectParsingErrors() { + void jsonObjectParsingErrors() { try { // does not start with '{' String str = "abc"; - assertNull("Expected an exception",new JSONObject(str)); + assertNull(new JSONObject(str),"Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "A JSONObject text must begin with '{' at 1 [character 2 line 1]", - e.getMessage()); + assertEquals("A JSONObject text must begin with '{' at 1 [character 2 line 1]", + e.getMessage(), + "Expecting an exception message"); } try { // does not end with '}' String str = "{"; - assertNull("Expected an exception",new JSONObject(str)); + assertNull(new JSONObject(str),"Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "A JSONObject text must end with '}' at 1 [character 2 line 1]", - e.getMessage()); + assertEquals("A JSONObject text must end with '}' at 1 [character 2 line 1]", + e.getMessage(), + "Expecting an exception message"); } try { // key with no ':' String str = "{\"myKey\" = true}"; - assertNull("Expected an exception",new JSONObject(str)); + assertNull(new JSONObject(str),"Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Expected a ':' after a key at 10 [character 11 line 1]", - e.getMessage()); + assertEquals("Expected a ':' after a key at 10 [character 11 line 1]", + e.getMessage(), + "Expecting an exception message"); } try { // entries with no ',' separator String str = "{\"myKey\":true \"myOtherKey\":false}"; - assertNull("Expected an exception",new JSONObject(str)); + assertNull(new JSONObject(str),"Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Expected a ',' or '}' at 15 [character 16 line 1]", - e.getMessage()); + assertEquals("Expected a ',' or '}' at 15 [character 16 line 1]", + e.getMessage(), + "Expecting an exception message"); } try { // key is a nested map String str = "{{\"foo\": \"bar\"}: \"baz\"}"; - assertNull("Expected an exception",new JSONObject(str)); + assertNull(new JSONObject(str),"Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Missing value at 1 [character 2 line 1]", - e.getMessage()); + assertEquals("Missing value at 1 [character 2 line 1]", + e.getMessage(), + "Expecting an exception message"); } try { // key is a nested array containing a map String str = "{\"a\": 1, [{\"foo\": \"bar\"}]: \"baz\"}"; - assertNull("Expected an exception",new JSONObject(str)); + assertNull(new JSONObject(str),"Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Missing value at 9 [character 10 line 1]", - e.getMessage()); + assertEquals("Missing value at 9 [character 10 line 1]", + e.getMessage(), + "Expecting an exception message"); } try { // key contains } String str = "{foo}: 2}"; - assertNull("Expected an exception",new JSONObject(str)); + assertNull(new JSONObject(str),"Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Expected a ':' after a key at 5 [character 6 line 1]", - e.getMessage()); + assertEquals("Expected a ':' after a key at 5 [character 6 line 1]", + e.getMessage(), + "Expecting an exception message"); } try { // key contains ] String str = "{foo]: 2}"; - assertNull("Expected an exception",new JSONObject(str)); + assertNull(new JSONObject(str),"Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Expected a ':' after a key at 5 [character 6 line 1]", - e.getMessage()); + assertEquals("Expected a ':' after a key at 5 [character 6 line 1]", + e.getMessage(), + "Expecting an exception message"); } try { // \0 after , String str = "{\"myKey\":true, \0\"myOtherKey\":false}"; - assertNull("Expected an exception",new JSONObject(str)); + assertNull(new JSONObject(str),"Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "A JSONObject text must end with '}' at 15 [character 16 line 1]", - e.getMessage()); + assertEquals("A JSONObject text must end with '}' at 15 [character 16 line 1]", + e.getMessage(), + "Expecting an exception message"); } try { // append to wrong key @@ -2351,9 +2209,9 @@ public void jsonObjectParsingErrors() { jsonObject.append("myKey", "hello"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "JSONObject[\"myKey\"] is not a JSONArray (null).", - e.getMessage()); + assertEquals("JSONObject[\"myKey\"] is not a JSONArray (null).", + e.getMessage(), + "Expecting an exception message"); } try { // increment wrong key @@ -2362,9 +2220,9 @@ public void jsonObjectParsingErrors() { jsonObject.increment("myKey"); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Unable to increment [\"myKey\"].", - e.getMessage()); + assertEquals("Unable to increment [\"myKey\"].", + e.getMessage(), + "Expecting an exception message"); } try { // invalid key @@ -2373,18 +2231,18 @@ public void jsonObjectParsingErrors() { jsonObject.get(null); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Null key.", - e.getMessage()); + assertEquals("Null key.", + e.getMessage(), + "Expecting an exception message"); } try { // invalid numberToString() JSONObject.numberToString((Number)null); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an exception message", - "Null pointer", - e.getMessage()); + assertEquals("Null pointer", + e.getMessage(), + "Expecting an exception message"); } try { @@ -2394,21 +2252,21 @@ public void jsonObjectParsingErrors() { jsonObject.putOnce("hello", "world!"); fail("Expected an exception"); } catch (JSONException e) { - assertTrue("", true); + assertTrue(true, ""); } try { // test validity of invalid double JSONObject.testValidity(NaN); fail("Expected an exception"); } catch (JSONException e) { - assertTrue("", true); + assertTrue(true, ""); } try { // test validity of invalid float JSONObject.testValidity(Float.NEGATIVE_INFINITY); fail("Expected an exception"); } catch (JSONException e) { - assertTrue("", true); + assertTrue(true, ""); } try { // test exception message when including a duplicate key (level 0) @@ -2421,9 +2279,9 @@ public void jsonObjectParsingErrors() { new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 90 [character 13 line 5]", - e.getMessage()); + assertEquals("Duplicate key \"attr03\" at 90 [character 13 line 5]", + e.getMessage(), + "Expecting an expection message"); } try { // test exception message when including a duplicate key (level 0) holding an object @@ -2440,9 +2298,9 @@ public void jsonObjectParsingErrors() { new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 90 [character 13 line 5]", - e.getMessage()); + assertEquals("Duplicate key \"attr03\" at 90 [character 13 line 5]", + e.getMessage(), + "Expecting an expection message"); } try { // test exception message when including a duplicate key (level 0) holding an array @@ -2461,9 +2319,9 @@ public void jsonObjectParsingErrors() { new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr03\" at 90 [character 13 line 5]", - e.getMessage()); + assertEquals("Duplicate key \"attr03\" at 90 [character 13 line 5]", + e.getMessage(), + "Expecting an expection message"); } try { // test exception message when including a duplicate key (level 1) @@ -2481,9 +2339,9 @@ public void jsonObjectParsingErrors() { new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", - e.getMessage()); + assertEquals("Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + e.getMessage(), + "Expecting an expection message"); } try { // test exception message when including a duplicate key (level 1) holding an object @@ -2505,9 +2363,9 @@ public void jsonObjectParsingErrors() { new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", - e.getMessage()); + assertEquals("Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + e.getMessage(), + "Expecting an expection message"); } try { // test exception message when including a duplicate key (level 1) holding an array @@ -2531,9 +2389,9 @@ public void jsonObjectParsingErrors() { new JSONObject(str); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr04-03\" at 215 [character 20 line 9]", - e.getMessage()); + assertEquals("Duplicate key \"attr04-03\" at 215 [character 20 line 9]", + e.getMessage(), + "Expecting an expection message"); } try { // test exception message when including a duplicate key in object (level 0) within an array @@ -2550,9 +2408,9 @@ public void jsonObjectParsingErrors() { new JSONArray(str); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr01\" at 124 [character 17 line 8]", - e.getMessage()); + assertEquals("Duplicate key \"attr01\" at 124 [character 17 line 8]", + e.getMessage(), + "Expecting an expection message"); } try { // test exception message when including a duplicate key in object (level 1) within an array @@ -2575,9 +2433,9 @@ public void jsonObjectParsingErrors() { new JSONArray(str); fail("Expected an exception"); } catch (JSONException e) { - assertEquals("Expecting an expection message", - "Duplicate key \"attr02-01\" at 269 [character 24 line 13]", - e.getMessage()); + assertEquals("Duplicate key \"attr02-01\" at 269 [character 24 line 13]", + e.getMessage(), + "Expecting an expection message"); } } @@ -2585,14 +2443,14 @@ public void jsonObjectParsingErrors() { * Confirm behavior when putOnce() is called with null parameters */ @Test - public void jsonObjectPutOnceNull() { + void jsonObjectPutOnceNull() { JSONObject jsonObject = new JSONObject(); jsonObject.putOnce(null, null); - assertTrue("jsonObject should be empty", jsonObject.isEmpty()); + assertTrue(jsonObject.isEmpty(), "jsonObject should be empty"); jsonObject.putOnce("", null); - assertTrue("jsonObject should be empty", jsonObject.isEmpty()); + assertTrue(jsonObject.isEmpty(), "jsonObject should be empty"); jsonObject.putOnce(null, ""); - assertTrue("jsonObject should be empty", jsonObject.isEmpty()); + assertTrue(jsonObject.isEmpty(), "jsonObject should be empty"); Util.checkJSONObjectMaps(jsonObject); } @@ -2600,129 +2458,99 @@ public void jsonObjectPutOnceNull() { * Exercise JSONObject opt(key, default) method. */ @Test - public void jsonObjectOptDefault() { + void jsonObjectOptDefault() { String str = "{\"myKey\": \"myval\", \"hiKey\": null}"; JSONObject jsonObject = new JSONObject(str); - assertTrue("optBigDecimal() should return default BigDecimal", - BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); - assertTrue("optBigInteger() should return default BigInteger", - BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); - assertTrue("optBoolean() should return default boolean", - jsonObject.optBoolean("myKey", true)); - assertTrue("optBooleanObject() should return default Boolean", - jsonObject.optBooleanObject("myKey", true)); - assertTrue("optInt() should return default int", - 42 == jsonObject.optInt("myKey", 42)); - assertTrue("optIntegerObject() should return default Integer", - Integer.valueOf(42).equals(jsonObject.optIntegerObject("myKey", 42))); - assertTrue("optEnum() should return default Enum", - MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); - assertTrue("optJSONArray() should return null ", - null==jsonObject.optJSONArray("myKey")); - assertTrue("optJSONArray() should return default JSONArray", - "value".equals(jsonObject.optJSONArray("myKey", new JSONArray("[\"value\"]")).getString(0))); - assertTrue("optJSONObject() should return default JSONObject ", - jsonObject.optJSONObject("myKey", new JSONObject("{\"testKey\":\"testValue\"}")).getString("testKey").equals("testValue")); - assertTrue("optLong() should return default long", - 42l == jsonObject.optLong("myKey", 42l)); - assertTrue("optLongObject() should return default Long", - Long.valueOf(42l).equals(jsonObject.optLongObject("myKey", 42l))); - assertTrue("optDouble() should return default double", - 42.3d == jsonObject.optDouble("myKey", 42.3d)); - assertTrue("optDoubleObject() should return default Double", - Double.valueOf(42.3d).equals(jsonObject.optDoubleObject("myKey", 42.3d))); - assertTrue("optFloat() should return default float", - 42.3f == jsonObject.optFloat("myKey", 42.3f)); - assertTrue("optFloatObject() should return default Float", - Float.valueOf(42.3f).equals(jsonObject.optFloatObject("myKey", 42.3f))); - assertTrue("optNumber() should return default Number", - 42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue()); - assertTrue("optString() should return default string", - "hi".equals(jsonObject.optString("hiKey", "hi"))); + assertEquals(0, BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN)), "optBigDecimal() should return default BigDecimal"); + assertEquals(0, BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey", BigInteger.TEN)), "optBigInteger() should return default BigInteger"); + assertTrue(jsonObject.optBoolean("myKey", true), + "optBoolean() should return default boolean"); + assertTrue(jsonObject.optBooleanObject("myKey", true), + "optBooleanObject() should return default Boolean"); + assertEquals(42, jsonObject.optInt("myKey", 42), "optInt() should return default int"); + assertEquals(Integer.valueOf(42), jsonObject.optIntegerObject("myKey", 42), "optIntegerObject() should return default Integer"); + assertEquals(MyEnum.VAL1, jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1), "optEnum() should return default Enum"); + assertTrue(null==jsonObject.optJSONArray("myKey"), + "optJSONArray() should return null "); + assertEquals("value", jsonObject.optJSONArray("myKey", new JSONArray("[\"value\"]")).getString(0), "optJSONArray() should return default JSONArray"); + assertEquals("testValue", jsonObject.optJSONObject("myKey", new JSONObject("{\"testKey\":\"testValue\"}")).getString("testKey"), "optJSONObject() should return default JSONObject "); + assertEquals(42l, jsonObject.optLong("myKey", 42l), "optLong() should return default long"); + assertEquals(Long.valueOf(42l), jsonObject.optLongObject("myKey", 42l), "optLongObject() should return default Long"); + assertEquals(42.3d, jsonObject.optDouble("myKey", 42.3d), "optDouble() should return default double"); + assertEquals(Double.valueOf(42.3d), jsonObject.optDoubleObject("myKey", 42.3d), "optDoubleObject() should return default Double"); + assertEquals(42.3f, jsonObject.optFloat("myKey", 42.3f), "optFloat() should return default float"); + assertEquals(Float.valueOf(42.3f), jsonObject.optFloatObject("myKey", 42.3f), "optFloatObject() should return default Float"); + assertEquals(42l, jsonObject.optNumber("myKey", Long.valueOf(42)).longValue(), "optNumber() should return default Number"); + assertEquals("hi", jsonObject.optString("hiKey", "hi"), "optString() should return default string"); Util.checkJSONObjectMaps(jsonObject); } - + /** * Exercise JSONObject opt(key, default) method when the key doesn't exist. */ @Test - public void jsonObjectOptNoKey() { + void jsonObjectOptNoKey() { JSONObject jsonObject = new JSONObject(); assertNull(jsonObject.opt(null)); - assertTrue("optBigDecimal() should return default BigDecimal", - BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN))==0); - assertTrue("optBigInteger() should return default BigInteger", - BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey",BigInteger.TEN ))==0); - assertTrue("optBoolean() should return default boolean", - jsonObject.optBoolean("myKey", true)); - assertTrue("optBooleanObject() should return default Boolean", - jsonObject.optBooleanObject("myKey", true)); - assertTrue("optInt() should return default int", - 42 == jsonObject.optInt("myKey", 42)); - assertTrue("optIntegerObject() should return default Integer", - Integer.valueOf(42).equals(jsonObject.optIntegerObject("myKey", 42))); - assertTrue("optEnum() should return default Enum", - MyEnum.VAL1.equals(jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1))); - assertTrue("optJSONArray() should return default JSONArray", - "value".equals(jsonObject.optJSONArray("myKey", new JSONArray("[\"value\"]")).getString(0))); - assertTrue("optJSONArray() should return null ", - null==jsonObject.optJSONArray("myKey")); - assertTrue("optJSONObject() should return default JSONObject ", - jsonObject.optJSONObject("myKey", new JSONObject("{\"testKey\":\"testValue\"}")).getString("testKey").equals("testValue")); - assertTrue("optLong() should return default long", - 42l == jsonObject.optLong("myKey", 42l)); - assertTrue("optLongObject() should return default Long", - Long.valueOf(42l).equals(jsonObject.optLongObject("myKey", 42l))); - assertTrue("optDouble() should return default double", - 42.3d == jsonObject.optDouble("myKey", 42.3d)); - assertTrue("optDoubleObject() should return default Double", - Double.valueOf(42.3d).equals(jsonObject.optDoubleObject("myKey", 42.3d))); - assertTrue("optFloat() should return default float", - 42.3f == jsonObject.optFloat("myKey", 42.3f)); - assertTrue("optFloatObject() should return default Float", - Float.valueOf(42.3f).equals(jsonObject.optFloatObject("myKey", 42.3f))); - assertTrue("optNumber() should return default Number", - 42l == jsonObject.optNumber("myKey", Long.valueOf(42)).longValue()); - assertTrue("optString() should return default string", - "hi".equals(jsonObject.optString("hiKey", "hi"))); + assertEquals(0, BigDecimal.TEN.compareTo(jsonObject.optBigDecimal("myKey", BigDecimal.TEN)), "optBigDecimal() should return default BigDecimal"); + assertEquals(0, BigInteger.TEN.compareTo(jsonObject.optBigInteger("myKey", BigInteger.TEN)), "optBigInteger() should return default BigInteger"); + assertTrue(jsonObject.optBoolean("myKey", true), + "optBoolean() should return default boolean"); + assertTrue(jsonObject.optBooleanObject("myKey", true), + "optBooleanObject() should return default Boolean"); + assertEquals(42, jsonObject.optInt("myKey", 42), "optInt() should return default int"); + assertEquals(Integer.valueOf(42), jsonObject.optIntegerObject("myKey", 42), "optIntegerObject() should return default Integer"); + assertEquals(MyEnum.VAL1, jsonObject.optEnum(MyEnum.class, "myKey", MyEnum.VAL1), "optEnum() should return default Enum"); + assertEquals("value", jsonObject.optJSONArray("myKey", new JSONArray("[\"value\"]")).getString(0), "optJSONArray() should return default JSONArray"); + assertTrue(null==jsonObject.optJSONArray("myKey"), + "optJSONArray() should return null "); + assertEquals("testValue", jsonObject.optJSONObject("myKey", new JSONObject("{\"testKey\":\"testValue\"}")).getString("testKey"), "optJSONObject() should return default JSONObject "); + assertEquals(42l, jsonObject.optLong("myKey", 42l), "optLong() should return default long"); + assertEquals(Long.valueOf(42l), jsonObject.optLongObject("myKey", 42l), "optLongObject() should return default Long"); + assertEquals(42.3d, jsonObject.optDouble("myKey", 42.3d), "optDouble() should return default double"); + assertEquals(Double.valueOf(42.3d), jsonObject.optDoubleObject("myKey", 42.3d), "optDoubleObject() should return default Double"); + assertEquals(42.3f, jsonObject.optFloat("myKey", 42.3f), "optFloat() should return default float"); + assertEquals(Float.valueOf(42.3f), jsonObject.optFloatObject("myKey", 42.3f), "optFloatObject() should return default Float"); + assertEquals(42l, jsonObject.optNumber("myKey", Long.valueOf(42)).longValue(), "optNumber() should return default Number"); + assertEquals("hi", jsonObject.optString("hiKey", "hi"), "optString() should return default string"); Util.checkJSONObjectMaps(jsonObject); } - + /** * Verifies that the opt methods properly convert string values. */ @Test - public void jsonObjectOptStringConversion() { + void jsonObjectOptStringConversion() { JSONObject jo = new JSONObject("{\"int\":\"123\",\"true\":\"true\",\"false\":\"false\"}"); - assertTrue("unexpected optBoolean value",jo.optBoolean("true",false)==true); - assertTrue("unexpected optBooleanObject value",Boolean.valueOf(true).equals(jo.optBooleanObject("true",false))); - assertTrue("unexpected optBoolean value",jo.optBoolean("false",true)==false); - assertTrue("unexpected optBooleanObject value",Boolean.valueOf(false).equals(jo.optBooleanObject("false",true))); - assertTrue("unexpected optInt value",jo.optInt("int",0)==123); - assertTrue("unexpected optIntegerObject value",Integer.valueOf(123).equals(jo.optIntegerObject("int",0))); - assertTrue("unexpected optLong value",jo.optLong("int",0)==123l); - assertTrue("unexpected optLongObject value",Long.valueOf(123l).equals(jo.optLongObject("int",0L))); - assertTrue("unexpected optDouble value",jo.optDouble("int",0.0d)==123.0d); - assertTrue("unexpected optDoubleObject value",Double.valueOf(123.0d).equals(jo.optDoubleObject("int",0.0d))); - assertTrue("unexpected optFloat value",jo.optFloat("int",0.0f)==123.0f); - assertTrue("unexpected optFloatObject value",Float.valueOf(123.0f).equals(jo.optFloatObject("int",0.0f))); - assertTrue("unexpected optBigInteger value",jo.optBigInteger("int",BigInteger.ZERO).compareTo(new BigInteger("123"))==0); - assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); - assertTrue("unexpected optBigDecimal value",jo.optBigDecimal("int",BigDecimal.ZERO).compareTo(new BigDecimal("123"))==0); - assertTrue("unexpected optNumber value",jo.optNumber("int",BigInteger.ZERO).longValue()==123l); + assertTrue(jo.optBoolean("true", false), "unexpected optBoolean value"); + assertEquals(Boolean.valueOf(true), jo.optBooleanObject("true", false), "unexpected optBooleanObject value"); + assertFalse(jo.optBoolean("false", true), "unexpected optBoolean value"); + assertEquals(Boolean.valueOf(false), jo.optBooleanObject("false", true), "unexpected optBooleanObject value"); + assertEquals(123, jo.optInt("int", 0), "unexpected optInt value"); + assertEquals(Integer.valueOf(123), jo.optIntegerObject("int", 0), "unexpected optIntegerObject value"); + assertEquals(123l, jo.optLong("int", 0), "unexpected optLong value"); + assertEquals(Long.valueOf(123l), jo.optLongObject("int", 0L), "unexpected optLongObject value"); + assertEquals(123.0d, jo.optDouble("int", 0.0d), "unexpected optDouble value"); + assertEquals(Double.valueOf(123.0d), jo.optDoubleObject("int", 0.0d), "unexpected optDoubleObject value"); + assertEquals(123.0f, jo.optFloat("int", 0.0f), "unexpected optFloat value"); + assertEquals(Float.valueOf(123.0f), jo.optFloatObject("int", 0.0f), "unexpected optFloatObject value"); + assertEquals(0, jo.optBigInteger("int", BigInteger.ZERO).compareTo(new BigInteger("123")), "unexpected optBigInteger value"); + assertEquals(0, jo.optBigDecimal("int", BigDecimal.ZERO).compareTo(new BigDecimal("123")), "unexpected optBigDecimal value"); + assertEquals(0, jo.optBigDecimal("int", BigDecimal.ZERO).compareTo(new BigDecimal("123")), "unexpected optBigDecimal value"); + assertEquals(123l, jo.optNumber("int", BigInteger.ZERO).longValue(), "unexpected optNumber value"); Util.checkJSONObjectMaps(jo); } - + /** * Verifies that the opt methods properly convert string values to numbers and coerce them consistently. */ @Test - public void jsonObjectOptCoercion() { + void jsonObjectOptCoercion() { JSONObject jo = new JSONObject("{\"largeNumberStr\":\"19007199254740993.35481234487103587486413587843213584\"}"); // currently the parser doesn't recognize BigDecimal, to we have to put it manually jo.put("largeNumber", new BigDecimal("19007199254740993.35481234487103587486413587843213584")); @@ -2764,12 +2592,12 @@ public void jsonObjectOptCoercion() { assertEquals(2147483647, (int)Double.parseDouble("19007199254740993.35481234487103587486413587843213584")); Util.checkJSONObjectMaps(jo); } - + /** * Verifies that the optBigDecimal method properly converts values to BigDecimal and coerce them consistently. */ @Test - public void jsonObjectOptBigDecimal() { + void jsonObjectOptBigDecimal() { JSONObject jo = new JSONObject().put("int", 123).put("long", 654L) .put("float", 1.234f).put("double", 2.345d) .put("bigInteger", new BigInteger("1234")) @@ -2787,12 +2615,12 @@ public void jsonObjectOptBigDecimal() { assertEquals(jo.optBigDecimal("double", null),jo.getBigDecimal("double")); Util.checkJSONObjectMaps(jo); } - + /** * Verifies that the optBigDecimal method properly converts values to BigDecimal and coerce them consistently. */ @Test - public void jsonObjectOptBigInteger() { + void jsonObjectOptBigInteger() { JSONObject jo = new JSONObject().put("int", 123).put("long", 654L) .put("float", 1.234f).put("double", 2.345d) .put("bigInteger", new BigInteger("1234")) @@ -2813,17 +2641,17 @@ public void jsonObjectOptBigInteger() { * Confirm behavior when JSONObject put(key, null object) is called */ @Test - public void jsonObjectputNull() { + void jsonObjectputNull() { // put null should remove the item. String str = "{\"myKey\": \"myval\"}"; JSONObject jsonObjectRemove = new JSONObject(str); jsonObjectRemove.remove("myKey"); - assertTrue("jsonObject should be empty", jsonObjectRemove.isEmpty()); + assertTrue(jsonObjectRemove.isEmpty(), "jsonObject should be empty"); JSONObject jsonObjectPutNull = new JSONObject(str); jsonObjectPutNull.put("myKey", (Object) null); - assertTrue("jsonObject should be empty", jsonObjectPutNull.isEmpty()); + assertTrue(jsonObjectPutNull.isEmpty(), "jsonObject should be empty"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jsonObjectRemove, jsonObjectPutNull ))); @@ -2835,41 +2663,33 @@ public void jsonObjectputNull() { * quotes, the quotes are properly escaped. */ @Test - public void jsonObjectQuote() { + void jsonObjectQuote() { String str; str = ""; String quotedStr; quotedStr = JSONObject.quote(str); - assertTrue("quote() expected escaped quotes, found "+quotedStr, - "\"\"".equals(quotedStr)); + assertEquals("\"\"", quotedStr, "quote() expected escaped quotes, found " + quotedStr); str = "\"\""; quotedStr = JSONObject.quote(str); - assertTrue("quote() expected escaped quotes, found "+quotedStr, - "\"\\\"\\\"\"".equals(quotedStr)); + assertEquals("\"\\\"\\\"\"", quotedStr, "quote() expected escaped quotes, found " + quotedStr); str = "null and null will be emitted as "" */ String sJONull = XML.toString(jsonObjectJONull); - assertTrue("JSONObject.NULL should emit a null value", - "null".equals(sJONull)); + assertEquals("null", sJONull, "JSONObject.NULL should emit a null value"); String sNull = XML.toString(jsonObjectNull); - assertTrue("null should emit an empty string", "".equals(sNull)); + assertEquals("", sNull, "null should emit an empty string"); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jsonObjectJONull, jsonObjectNull ))); } - - @Test(expected = JSONPointerException.class) - public void queryWithNoResult() { - new JSONObject().query("/a/b"); + + @Test + void queryWithNoResult() { + assertThrows(JSONPointerException.class, () -> { + new JSONObject().query("/a/b"); + }); } - + @Test - public void optQueryWithNoResult() { + void optQueryWithNoResult() { assertNull(new JSONObject().optQuery("/a/b")); } - - @Test(expected = IllegalArgumentException.class) - public void optQueryWithSyntaxError() { - new JSONObject().optQuery("invalid"); + + @Test + void optQueryWithSyntaxError() { + assertThrows(IllegalArgumentException.class, () -> { + new JSONObject().optQuery("invalid"); + }); } - @Test(expected = JSONException.class) - public void invalidEscapeSequence() { - String json = "{ \"\\url\": \"value\" }"; - assertNull("Expected an exception",new JSONObject(json)); + @Test + void invalidEscapeSequence() { + assertThrows(JSONException.class, () -> { + String json = "{ \"\\url\": \"value\" }"; + assertNull(new JSONObject(json), "Expected an exception"); + }); } /** * Exercise JSONObject toMap() method. */ @Test - public void toMap() { + void toMap() { String jsonObjectStr = "{" + "\"key1\":" + @@ -3244,66 +3065,66 @@ public void toMap() { JSONObject jsonObject = new JSONObject(jsonObjectStr); Map map = jsonObject.toMap(); - assertTrue("Map should not be null", map != null); - assertTrue("Map should have 3 elements", map.size() == 3); + assertTrue(map != null, "Map should not be null"); + assertEquals(3, map.size(), "Map should have 3 elements"); List key1List = (List)map.get("key1"); - assertTrue("key1 should not be null", key1List != null); - assertTrue("key1 list should have 3 elements", key1List.size() == 3); - assertTrue("key1 value 1 should be 1", key1List.get(0).equals(Integer.valueOf(1))); - assertTrue("key1 value 2 should be 2", key1List.get(1).equals(Integer.valueOf(2))); + assertTrue(key1List != null, "key1 should not be null"); + assertEquals(3, key1List.size(), "key1 list should have 3 elements"); + assertEquals(key1List.get(0), Integer.valueOf(1), "key1 value 1 should be 1"); + assertEquals(key1List.get(1), Integer.valueOf(2), "key1 value 2 should be 2"); Map key1Value3Map = (Map)key1List.get(2); - assertTrue("Map should not be null", key1Value3Map != null); - assertTrue("Map should have 1 element", key1Value3Map.size() == 1); - assertTrue("Map key3 should be true", key1Value3Map.get("key3").equals(Boolean.TRUE)); + assertTrue(key1Value3Map != null, "Map should not be null"); + assertEquals(1, key1Value3Map.size(), "Map should have 1 element"); + assertEquals(Boolean.TRUE, key1Value3Map.get("key3"), "Map key3 should be true"); Map key2Map = (Map)map.get("key2"); - assertTrue("key2 should not be null", key2Map != null); - assertTrue("key2 map should have 3 elements", key2Map.size() == 3); - assertTrue("key2 map key 1 should be val1", key2Map.get("key1").equals("val1")); - assertTrue("key2 map key 3 should be 42", key2Map.get("key3").equals(Integer.valueOf(42))); + assertTrue(key2Map != null, "key2 should not be null"); + assertEquals(3, key2Map.size(), "key2 map should have 3 elements"); + assertEquals("val1", key2Map.get("key1"), "key2 map key 1 should be val1"); + assertEquals(key2Map.get("key3"), Integer.valueOf(42), "key2 map key 3 should be 42"); Map key2Val2Map = (Map)key2Map.get("key2"); - assertTrue("key2 map key 2 should not be null", key2Val2Map != null); - assertTrue("key2 map key 2 should have an entry", key2Val2Map.containsKey("key2")); - assertTrue("key2 map key 2 value should be null", key2Val2Map.get("key2") == null); + assertTrue(key2Val2Map != null, "key2 map key 2 should not be null"); + assertTrue(key2Val2Map.containsKey("key2"), "key2 map key 2 should have an entry"); + assertTrue(key2Val2Map.get("key2") == null, "key2 map key 2 value should be null"); List key3List = (List)map.get("key3"); - assertTrue("key3 should not be null", key3List != null); - assertTrue("key3 list should have 3 elements", key3List.size() == 2); + assertTrue(key3List != null, "key3 should not be null"); + assertEquals(2, key3List.size(), "key3 list should have 3 elements"); List key3Val1List = (List)key3List.get(0); - assertTrue("key3 list val 1 should not be null", key3Val1List != null); - assertTrue("key3 list val 1 should have 2 elements", key3Val1List.size() == 2); - assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); - assertTrue("key3 list val 1 list element 2 should be 2.1", key3Val1List.get(1).equals(new BigDecimal("2.1"))); + assertTrue(key3Val1List != null, "key3 list val 1 should not be null"); + assertEquals(2, key3Val1List.size(), "key3 list val 1 should have 2 elements"); + assertEquals("value1", key3Val1List.get(0), "key3 list val 1 list element 1 should be value1"); + assertEquals(key3Val1List.get(1), new BigDecimal("2.1"), "key3 list val 1 list element 2 should be 2.1"); List key3Val2List = (List)key3List.get(1); - assertTrue("key3 list val 2 should not be null", key3Val2List != null); - assertTrue("key3 list val 2 should have 1 element", key3Val2List.size() == 1); - assertTrue("key3 list val 2 list element 1 should be null", key3Val2List.get(0) == null); + assertTrue(key3Val2List != null, "key3 list val 2 should not be null"); + assertEquals(1, key3Val2List.size(), "key3 list val 2 should have 1 element"); + assertTrue(key3Val2List.get(0) == null, "key3 list val 2 list element 1 should be null"); // Assert that toMap() is a deep copy jsonObject.getJSONArray("key3").getJSONArray(0).put(0, "still value 1"); - assertTrue("key3 list val 1 list element 1 should be value1", key3Val1List.get(0).equals("value1")); + assertEquals("value1", key3Val1List.get(0), "key3 list val 1 list element 1 should be value1"); // assert that the new map is mutable - assertTrue("Removing a key should succeed", map.remove("key3") != null); - assertTrue("Map should have 2 elements", map.size() == 2); + assertTrue(map.remove("key3") != null, "Removing a key should succeed"); + assertEquals(2, map.size(), "Map should have 2 elements"); Util.checkJSONObjectMaps(jsonObject); } - + /** * test that validates a singleton can be serialized as a bean. */ @SuppressWarnings("boxing") @Test - public void testSingletonBean() { + void singletonBean() { final JSONObject jo = new JSONObject(Singleton.getInstance()); - assertEquals(jo.keySet().toString(), 1, jo.length()); + assertEquals(1, jo.length(), jo.keySet().toString()); assertEquals(0, jo.get("someInt")); - assertEquals(null, jo.opt("someString")); + assertNull(jo.opt("someString")); // Update the singleton values Singleton.getInstance().setSomeInt(42); @@ -3315,7 +3136,7 @@ public void testSingletonBean() { // ensure our original jo hasn't changed. assertEquals(0, jo.get("someInt")); - assertEquals(null, jo.opt("someString")); + assertNull(jo.opt("someString")); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jo, jo2 ))); @@ -3326,11 +3147,11 @@ public void testSingletonBean() { */ @SuppressWarnings("boxing") @Test - public void testSingletonEnumBean() { + void singletonEnumBean() { final JSONObject jo = new JSONObject(SingletonEnum.getInstance()); - assertEquals(jo.keySet().toString(), 1, jo.length()); + assertEquals(1, jo.length(), jo.keySet().toString()); assertEquals(0, jo.get("someInt")); - assertEquals(null, jo.opt("someString")); + assertNull(jo.opt("someString")); // Update the singleton values SingletonEnum.getInstance().setSomeInt(42); @@ -3342,49 +3163,47 @@ public void testSingletonEnumBean() { // ensure our original jo hasn't changed. assertEquals(0, jo.get("someInt")); - assertEquals(null, jo.opt("someString")); + assertNull(jo.opt("someString")); Util.checkJSONObjectsMaps(new ArrayList(Arrays.asList( jo, jo2 ))); } - + /** * Test to validate that a generic class can be serialized as a bean. */ @SuppressWarnings("boxing") @Test - public void testGenericBean() { + void genericBean() { GenericBean bean = new GenericBean<>(42); final JSONObject jo = new JSONObject(bean); - assertEquals(jo.keySet().toString(), 8, jo.length()); + assertEquals(8, jo.length(), jo.keySet().toString()); assertEquals(42, jo.get("genericValue")); - assertEquals("Expected the getter to only be called once", - 1, bean.genericGetCounter); + assertEquals(1, bean.genericGetCounter, "Expected the getter to only be called once"); assertEquals(0, bean.genericSetCounter); Util.checkJSONObjectMaps(jo); } - + /** * Test to validate that a generic class can be serialized as a bean. */ @SuppressWarnings("boxing") @Test - public void testGenericIntBean() { + void genericIntBean() { GenericBeanInt bean = new GenericBeanInt(42); final JSONObject jo = new JSONObject(bean); - assertEquals(jo.keySet().toString(), 10, jo.length()); + assertEquals(10, jo.length(), jo.keySet().toString()); assertEquals(42, jo.get("genericValue")); - assertEquals("Expected the getter to only be called once", - 1, bean.genericGetCounter); + assertEquals(1, bean.genericGetCounter, "Expected the getter to only be called once"); assertEquals(0, bean.genericSetCounter); Util.checkJSONObjectMaps(jo); } - + /** * Test to verify key limitations in the JSONObject bean serializer. */ @Test - public void testWierdListBean() { + void wierdListBean() { @SuppressWarnings("boxing") WeirdList bean = new WeirdList(42, 43, 44); final JSONObject jo = new JSONObject(bean); @@ -3393,18 +3212,17 @@ public void testWierdListBean() { // getInt(int) should also be ignored based on parameter count // add(Integer) should be ignore as it doesn't start with get/is and also has a parameter // getALL should be mapped - assertEquals("Expected 1 key to be mapped. Instead found: "+jo.keySet().toString(), - 1, jo.length()); + assertEquals(1, jo.length(), "Expected 1 key to be mapped. Instead found: "+jo.keySet().toString()); assertNotNull(jo.get("ALL")); Util.checkJSONObjectMaps(jo); } - + /** * Sample test case from https://github.com/stleary/JSON-java/issues/531 * which verifies that no regression in double/BigDecimal support is present. */ @Test - public void testObjectToBigDecimal() { + void objectToBigDecimal() { double value = 1412078745.01074; Reader reader = new StringReader("[{\"value\": " + value + "}]"); JSONTokener tokener = new JSONTokener(reader); @@ -3418,137 +3236,175 @@ public void testObjectToBigDecimal() { Util.checkJSONObjectMaps(jsonObject); Util.checkJSONArrayMaps(array, jsonObject.getMapType()); } - + /** * Tests the exception portions of populateMap. */ @Test - public void testExceptionalBean() { + void exceptionalBean() { ExceptionalBean bean = new ExceptionalBean(); final JSONObject jo = new JSONObject(bean); - assertEquals("Expected 1 key to be mapped. Instead found: "+jo.keySet().toString(), - 1, jo.length()); + assertEquals(1, jo.length(), "Expected 1 key to be mapped. Instead found: "+jo.keySet().toString()); assertTrue(jo.get("closeable") instanceof JSONObject); assertTrue(jo.getJSONObject("closeable").has("string")); Util.checkJSONObjectMaps(jo); } - - @Test(expected=NullPointerException.class) - public void testPutNullBoolean() { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, false); - fail("Expected an exception"); - } - @Test(expected=NullPointerException.class) - public void testPutNullCollection() { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, Collections.emptySet()); - fail("Expected an exception"); - } - @Test(expected=NullPointerException.class) - public void testPutNullDouble() { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, 0.0d); - fail("Expected an exception"); - } - @Test(expected=NullPointerException.class) - public void testPutNullFloat() { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, 0.0f); - fail("Expected an exception"); - } - @Test(expected=NullPointerException.class) - public void testPutNullInt() { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, 0); - fail("Expected an exception"); - } - @Test(expected=NullPointerException.class) - public void testPutNullLong() { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, 0L); - fail("Expected an exception"); - } - @Test(expected=NullPointerException.class) - public void testPutNullMap() { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, Collections.emptyMap()); - fail("Expected an exception"); - } - @Test(expected=NullPointerException.class) - public void testPutNullObject() { - // null put key - JSONObject jsonObject = new JSONObject("{}"); - jsonObject.put(null, new Object()); - fail("Expected an exception"); - } - @Test(expected=JSONException.class) - public void testSelfRecursiveObject() { - // A -> A ... - RecursiveBean ObjA = new RecursiveBean("ObjA"); - ObjA.setRef(ObjA); - new JSONObject(ObjA); - fail("Expected an exception"); + + @Test + void putNullBoolean() { + assertThrows(NullPointerException.class, () -> { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, false); + fail("Expected an exception"); + }); } - @Test(expected=JSONException.class) - public void testLongSelfRecursiveObject() { - // B -> A -> A ... - RecursiveBean ObjA = new RecursiveBean("ObjA"); - RecursiveBean ObjB = new RecursiveBean("ObjB"); - ObjB.setRef(ObjA); - ObjA.setRef(ObjA); - new JSONObject(ObjB); - fail("Expected an exception"); + + @Test + void putNullCollection() { + assertThrows(NullPointerException.class, () -> { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, Collections.emptySet()); + fail("Expected an exception"); + }); } - @Test(expected=JSONException.class) - public void testSimpleRecursiveObject() { - // B -> A -> B ... - RecursiveBean ObjA = new RecursiveBean("ObjA"); - RecursiveBean ObjB = new RecursiveBean("ObjB"); - ObjB.setRef(ObjA); - ObjA.setRef(ObjB); - new JSONObject(ObjA); - fail("Expected an exception"); + + @Test + void putNullDouble() { + assertThrows(NullPointerException.class, () -> { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0.0d); + fail("Expected an exception"); + }); } - @Test(expected=JSONException.class) - public void testLongRecursiveObject() { - // D -> C -> B -> A -> D ... - RecursiveBean ObjA = new RecursiveBean("ObjA"); - RecursiveBean ObjB = new RecursiveBean("ObjB"); - RecursiveBean ObjC = new RecursiveBean("ObjC"); - RecursiveBean ObjD = new RecursiveBean("ObjD"); - ObjC.setRef(ObjB); - ObjB.setRef(ObjA); - ObjD.setRef(ObjC); - ObjA.setRef(ObjD); - new JSONObject(ObjB); - fail("Expected an exception"); + + @Test + void putNullFloat() { + assertThrows(NullPointerException.class, () -> { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0.0f); + fail("Expected an exception"); + }); } - @Test(expected=JSONException.class) - public void testRepeatObjectRecursive() { - // C -> B -> A -> D -> C ... - // -> D -> C ... - RecursiveBean ObjA = new RecursiveBean("ObjA"); - RecursiveBean ObjB = new RecursiveBean("ObjB"); - RecursiveBean ObjC = new RecursiveBean("ObjC"); - RecursiveBean ObjD = new RecursiveBean("ObjD"); - ObjC.setRef(ObjB); - ObjB.setRef(ObjA); - ObjB.setRef2(ObjD); - ObjA.setRef(ObjD); - ObjD.setRef(ObjC); - new JSONObject(ObjC); - fail("Expected an exception"); + + @Test + void putNullInt() { + assertThrows(NullPointerException.class, () -> { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0); + fail("Expected an exception"); + }); + } + + @Test + void putNullLong() { + assertThrows(NullPointerException.class, () -> { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, 0L); + fail("Expected an exception"); + }); + } + + @Test + void putNullMap() { + assertThrows(NullPointerException.class, () -> { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, Collections.emptyMap()); + fail("Expected an exception"); + }); + } + + @Test + void putNullObject() { + assertThrows(NullPointerException.class, () -> { + // null put key + JSONObject jsonObject = new JSONObject("{}"); + jsonObject.put(null, new Object()); + fail("Expected an exception"); + }); + } + + @Test + void selfRecursiveObject() { + assertThrows(JSONException.class, () -> { + // A -> A ... + RecursiveBean ObjA = new RecursiveBean("ObjA"); + ObjA.setRef(ObjA); + new JSONObject(ObjA); + fail("Expected an exception"); + }); } + @Test - public void testRepeatObjectNotRecursive() { + void longSelfRecursiveObject() { + assertThrows(JSONException.class, () -> { + // B -> A -> A ... + RecursiveBean ObjA = new RecursiveBean("ObjA"); + RecursiveBean ObjB = new RecursiveBean("ObjB"); + ObjB.setRef(ObjA); + ObjA.setRef(ObjA); + new JSONObject(ObjB); + fail("Expected an exception"); + }); + } + + @Test + void simpleRecursiveObject() { + assertThrows(JSONException.class, () -> { + // B -> A -> B ... + RecursiveBean ObjA = new RecursiveBean("ObjA"); + RecursiveBean ObjB = new RecursiveBean("ObjB"); + ObjB.setRef(ObjA); + ObjA.setRef(ObjB); + new JSONObject(ObjA); + fail("Expected an exception"); + }); + } + + @Test + void longRecursiveObject() { + assertThrows(JSONException.class, () -> { + // D -> C -> B -> A -> D ... + RecursiveBean ObjA = new RecursiveBean("ObjA"); + RecursiveBean ObjB = new RecursiveBean("ObjB"); + RecursiveBean ObjC = new RecursiveBean("ObjC"); + RecursiveBean ObjD = new RecursiveBean("ObjD"); + ObjC.setRef(ObjB); + ObjB.setRef(ObjA); + ObjD.setRef(ObjC); + ObjA.setRef(ObjD); + new JSONObject(ObjB); + fail("Expected an exception"); + }); + } + + @Test + void repeatObjectRecursive() { + assertThrows(JSONException.class, () -> { + // C -> B -> A -> D -> C ... + // -> D -> C ... + RecursiveBean ObjA = new RecursiveBean("ObjA"); + RecursiveBean ObjB = new RecursiveBean("ObjB"); + RecursiveBean ObjC = new RecursiveBean("ObjC"); + RecursiveBean ObjD = new RecursiveBean("ObjD"); + ObjC.setRef(ObjB); + ObjB.setRef(ObjA); + ObjB.setRef2(ObjD); + ObjA.setRef(ObjD); + ObjD.setRef(ObjC); + new JSONObject(ObjC); + fail("Expected an exception"); + }); + } + + @Test + void repeatObjectNotRecursive() { // C -> B -> A // -> A RecursiveBean ObjA = new RecursiveBean("ObjA"); @@ -3564,8 +3420,9 @@ public void testRepeatObjectNotRecursive() { j0, j1, j2 ))); } + @Test - public void testLongRepeatObjectNotRecursive() { + void longRepeatObjectNotRecursive() { // C -> B -> A -> D -> E // -> D -> E RecursiveBean ObjA = new RecursiveBean("ObjA"); @@ -3587,15 +3444,19 @@ public void testLongRepeatObjectNotRecursive() { j0, j1, j2, j3, j4 ))); } - @Test(expected=JSONException.class) - public void testRecursiveEquals() { - RecursiveBeanEquals a = new RecursiveBeanEquals("same"); - a.setRef(a); - JSONObject j0 = new JSONObject(a); - Util.checkJSONObjectMaps(j0); + + @Test + void recursiveEquals() { + assertThrows(JSONException.class, () -> { + RecursiveBeanEquals a = new RecursiveBeanEquals("same"); + a.setRef(a); + JSONObject j0 = new JSONObject(a); + Util.checkJSONObjectMaps(j0); + }); } + @Test - public void testNotRecursiveEquals() { + void notRecursiveEquals() { RecursiveBeanEquals a = new RecursiveBeanEquals("same"); RecursiveBeanEquals b = new RecursiveBeanEquals("same"); RecursiveBeanEquals c = new RecursiveBeanEquals("same"); @@ -3607,80 +3468,90 @@ public void testNotRecursiveEquals() { @Test - public void testIssue548ObjectWithEmptyJsonArray() { + void issue548ObjectWithEmptyJsonArray() { JSONObject jsonObject = new JSONObject("{\"empty_json_array\": []}"); - assertTrue("missing expected key 'empty_json_array'", jsonObject.has("empty_json_array")); - assertNotNull("'empty_json_array' should be an array", jsonObject.getJSONArray("empty_json_array")); - assertEquals("'empty_json_array' should have a length of 0", 0, jsonObject.getJSONArray("empty_json_array").length()); + assertTrue(jsonObject.has("empty_json_array"), "missing expected key 'empty_json_array'"); + assertNotNull(jsonObject.getJSONArray("empty_json_array"), "'empty_json_array' should be an array"); + assertEquals(0, jsonObject.getJSONArray("empty_json_array").length(), "'empty_json_array' should have a length of 0"); Util.checkJSONObjectMaps(jsonObject); } /** * Tests if calling JSONObject clear() method actually makes the JSONObject empty */ - @Test(expected = JSONException.class) - public void jsonObjectClearMethodTest() { - //Adds random stuff to the JSONObject - JSONObject jsonObject = new JSONObject(); - jsonObject.put("key1", 123); - jsonObject.put("key2", "456"); - jsonObject.put("key3", new JSONObject()); - jsonObject.clear(); //Clears the JSONObject - assertTrue("expected jsonObject.length() == 0", jsonObject.length() == 0); //Check if its length is 0 - jsonObject.getInt("key1"); //Should throws org.json.JSONException: JSONObject["asd"] not found - Util.checkJSONObjectMaps(jsonObject); + @Test + void jsonObjectClearMethodTest() { + assertThrows(JSONException.class, () -> { + //Adds random stuff to the JSONObject + JSONObject jsonObject = new JSONObject(); + jsonObject.put("key1", 123); + jsonObject.put("key2", "456"); + jsonObject.put("key3", new JSONObject()); + jsonObject.clear(); //Clears the JSONObject + assertEquals(0, jsonObject.length(), "expected jsonObject.length() == 0"); //Check if its length is 0 + jsonObject.getInt("key1"); //Should throws org.json.JSONException: JSONObject["asd"] not found + Util.checkJSONObjectMaps(jsonObject); + }); } /** * Tests for stack overflow. See https://github.com/stleary/JSON-java/issues/654 */ - @Test(expected = JSONException.class) - public void issue654StackOverflowInput() { - //String base64Bytes ="eyJHWiI6Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMCkwLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7CXt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMCkwLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7CXt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3sJe3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTApMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3sJe3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTApMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMCkwLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7CXt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMCkwLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7CXt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3sJe3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTApMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3sJe3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTApMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7c3t7e3t7e3vPAAAAAAAAAHt7e3t7e3t7e3t7e3t7e3t7e3t7e1ste3t7e3t7e3t7e3t7e3t7e3t7e3t7CXt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e88AAAAAAAAAe3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7f3syMv//e3t7e3t7e3t7e3t7e3sx//////8="; - //String input = new String(java.util.Base64.getDecoder().decode(base64Bytes)); - String input = "{\"GZ\":[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{s{{{{{{{"; - JSONObject json_input = new JSONObject(input); - assertNotNull(json_input); - fail("Excepected Exception."); - Util.checkJSONObjectMaps(json_input); + @Test + void issue654StackOverflowInput() { + assertThrows(JSONException.class, () -> { + //String base64Bytes ="eyJHWiI6Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMCkwLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7CXt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMCkwLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7CXt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3sJe3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTApMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3sJe3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTApMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMCkwLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7CXt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMCkwLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7CXt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3sJe3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTApMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3sJe3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTApMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7ewl7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7c3t7e3t7e3vPAAAAAAAAAHt7e3t7e3t7e3t7e3t7e3t7e3t7e1ste3t7e3t7e3t7e3t7e3t7e3t7e3t7CXt7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3tbLTAtMCx7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e1stMC0wLHt7e3t7e3t7e3t7e3t7e3t7e88AAAAAAAAAe3t7e3t7e3t7e3t7e3t7e3t7e3t7Wy0wLTAse3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7f3syMv//e3t7e3t7e3t7e3t7e3sx//////8="; + //String input = new String(java.util.Base64.getDecoder().decode(base64Bytes)); + String input = "{\"GZ\":[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0)0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{{{{{{{{{{{{{{{{{{{{[-0-0,{{{{{{{{{{s{{{{{{{"; + JSONObject json_input = new JSONObject(input); + assertNotNull(json_input); + fail("Excepected Exception."); + Util.checkJSONObjectMaps(json_input); + }); } /** * Tests for incorrect object/array nesting. See https://github.com/stleary/JSON-java/issues/654 */ - @Test(expected = JSONException.class) - public void issue654IncorrectNestingNoKey1() { - JSONObject json_input = new JSONObject("{{\"a\":0}}"); - assertNotNull(json_input); - fail("Expected Exception."); + @Test + void issue654IncorrectNestingNoKey1() { + assertThrows(JSONException.class, () -> { + JSONObject json_input = new JSONObject("{{\"a\":0}}"); + assertNotNull(json_input); + fail("Expected Exception."); + }); } /** * Tests for incorrect object/array nesting. See https://github.com/stleary/JSON-java/issues/654 */ - @Test(expected = JSONException.class) - public void issue654IncorrectNestingNoKey2() { - JSONObject json_input = new JSONObject("{[\"a\"]}"); - assertNotNull(json_input); - fail("Excepected Exception."); + @Test + void issue654IncorrectNestingNoKey2() { + assertThrows(JSONException.class, () -> { + JSONObject json_input = new JSONObject("{[\"a\"]}"); + assertNotNull(json_input); + fail("Excepected Exception."); + }); } - + /** * Tests for stack overflow. See https://github.com/stleary/JSON-java/issues/654 */ - @Ignore("This test relies on system constraints and may not always pass. See: https://github.com/stleary/JSON-java/issues/821") - @Test(expected = JSONException.class) - public void issue654StackOverflowInputWellFormed() { - //String input = new String(java.util.Base64.getDecoder().decode(base64Bytes)); - final InputStream resourceAsStream = JSONObjectTest.class.getClassLoader().getResourceAsStream("Issue654WellFormedObject.json"); - JSONTokener tokener = new JSONTokener(resourceAsStream); - JSONObject json_input = new JSONObject(tokener); - assertNotNull(json_input); - fail("Excepected Exception due to stack overflow."); + @Disabled("This test relies on system constraints and may not always pass. See: https://github.com/stleary/JSON-java/issues/821") + @Test + void issue654StackOverflowInputWellFormed() { + assertThrows(JSONException.class, () -> { + //String input = new String(java.util.Base64.getDecoder().decode(base64Bytes)); + final InputStream resourceAsStream = JSONObjectTest.class.getClassLoader().getResourceAsStream("Issue654WellFormedObject.json"); + JSONTokener tokener = new JSONTokener(resourceAsStream); + JSONObject json_input = new JSONObject(tokener); + assertNotNull(json_input); + fail("Excepected Exception due to stack overflow."); + }); } @Test - public void testIssue682SimilarityOfJSONString() { + void issue682SimilarityOfJSONString() { JSONObject jo1 = new JSONObject() .put("a", new MyJsonString()) .put("b", 2); @@ -3704,7 +3575,7 @@ public String toJSONString() { Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY, Float.NaN }; @Test - public void issue713MapConstructorWithNonFiniteNumbers() { + void issue713MapConstructorWithNonFiniteNumbers() { for (Number nonFinite : NON_FINITE_NUMBERS) { Map map = new HashMap<>(); map.put("a", nonFinite); @@ -3714,50 +3585,56 @@ public void issue713MapConstructorWithNonFiniteNumbers() { } @Test - public void issue713BeanConstructorWithNonFiniteNumbers() { + void issue713BeanConstructorWithNonFiniteNumbers() { for (Number nonFinite : NON_FINITE_NUMBERS) { GenericBean bean = new GenericBean<>(nonFinite); assertThrows(JSONException.class, () -> new JSONObject(bean)); } } - @Test(expected = JSONException.class) - public void issue743SerializationMap() { - HashMap map = new HashMap<>(); - map.put("t", map); - JSONObject object = new JSONObject(map); - String jsonString = object.toString(); + @Test + void issue743SerializationMap() { + assertThrows(JSONException.class, () -> { + HashMap map = new HashMap<>(); + map.put("t", map); + JSONObject object = new JSONObject(map); + String jsonString = object.toString(); + }); } - @Test(expected = JSONException.class) - public void testCircularReferenceMultipleLevel() { - HashMap inside = new HashMap<>(); - HashMap jsonObject = new HashMap<>(); - inside.put("inside", jsonObject); - jsonObject.put("test", inside); - new JSONObject(jsonObject); + @Test + void circularReferenceMultipleLevel() { + assertThrows(JSONException.class, () -> { + HashMap inside = new HashMap<>(); + HashMap jsonObject = new HashMap<>(); + inside.put("inside", jsonObject); + jsonObject.put("test", inside); + new JSONObject(jsonObject); + }); } @Test - public void issue743SerializationMapWith512Objects() { + void issue743SerializationMapWith512Objects() { HashMap map = buildNestedMap(ParserConfiguration.DEFAULT_MAXIMUM_NESTING_DEPTH); JSONObject object = new JSONObject(map); String jsonString = object.toString(); } @Test - public void issue743SerializationMapWith1000Objects() { + void issue743SerializationMapWith1000Objects() { HashMap map = buildNestedMap(1000); JSONParserConfiguration parserConfiguration = new JSONParserConfiguration().withMaxNestingDepth(1000); JSONObject object = new JSONObject(map, parserConfiguration); String jsonString = object.toString(); } - @Test(expected = JSONException.class) - public void issue743SerializationMapWith1001Objects() { - HashMap map = buildNestedMap(1001); - JSONObject object = new JSONObject(map); - String jsonString = object.toString(); + @Test + void issue743SerializationMapWith1001Objects() { + assertThrows(JSONException.class, () -> { + HashMap map = buildNestedMap(1001); + JSONObject object = new JSONObject(map); + String jsonString = object.toString(); + }); } /** diff --git a/src/test/java/org/json/junit/JSONPointerTest.java b/src/test/java/org/json/junit/JSONPointerTest.java index 45c7dbd3d..61339b2ce 100644 --- a/src/test/java/org/json/junit/JSONPointerTest.java +++ b/src/test/java/org/json/junit/JSONPointerTest.java @@ -4,9 +4,7 @@ Public Domain. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.io.InputStream; @@ -15,9 +13,9 @@ import org.json.JSONPointer; import org.json.JSONPointerException; import org.json.JSONTokener; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class JSONPointerTest { +class JSONPointerTest { private static final JSONObject document; private static final String EXPECTED_COMPLETE_DOCUMENT = "{\"\":0,\" \":7,\"g|h\":4,\"c%d\":2,\"k\\\"l\":6,\"a/b\":1,\"i\\\\j\":5," + @@ -40,38 +38,42 @@ private Object query(String pointer) { } @Test - public void emptyPointer() { + void emptyPointer() { assertTrue(new JSONObject(EXPECTED_COMPLETE_DOCUMENT).similar(query(""))); } @SuppressWarnings("unused") - @Test(expected = NullPointerException.class) - public void nullPointer() { - new JSONPointer((String) null); + @Test + void nullPointer() { + assertThrows(NullPointerException.class, () -> { + new JSONPointer((String)null); + }); } @Test - public void objectPropertyQuery() { + void objectPropertyQuery() { assertEquals("[\"bar\",\"baz\"]", query("/foo").toString()); } @Test - public void arrayIndexQuery() { + void arrayIndexQuery() { assertEquals("bar", query("/foo/0")); } - @Test(expected = JSONPointerException.class) - public void stringPropOfArrayFailure() { - query("/foo/bar"); + @Test + void stringPropOfArrayFailure() { + assertThrows(JSONPointerException.class, () -> { + query("/foo/bar"); + }); } @Test - public void queryByEmptyKey() { + void queryByEmptyKey() { assertEquals(0, query("/")); } @Test - public void queryByEmptyKeySubObject() { + void queryByEmptyKeySubObject() { JSONObject json = new JSONObject("{\"\":\"empty key of an object with an empty key\",\"subKey\":\"Some" + " other value\"}"); JSONObject obj = (JSONObject) query("/obj/"); @@ -79,22 +81,22 @@ public void queryByEmptyKeySubObject() { } @Test - public void queryByEmptyKeySubObjectSubOject() { + void queryByEmptyKeySubObjectSubOject() { assertEquals("empty key of an object with an empty key", query("/obj//")); } - + @Test - public void queryByEmptyKeySubObjectValue() { + void queryByEmptyKeySubObjectValue() { assertEquals("Some other value", query("/obj//subKey")); } @Test - public void slashEscaping() { + void slashEscaping() { assertEquals(1, query("/a~1b")); } @Test - public void tildeEscaping() { + void tildeEscaping() { assertEquals(8, query("/m~0n")); } @@ -104,37 +106,37 @@ public void tildeEscaping() { * @see rfc6901 section 3 */ @Test - public void backslashHandling() { + void backslashHandling() { assertEquals(5, query("/i\\j")); } - + /** * We pass quotations as-is * * @see rfc6901 section 3 */ @Test - public void quotationHandling() { + void quotationHandling() { assertEquals(6, query("/k\"l")); } - + @Test - public void whitespaceKey() { + void whitespaceKey() { assertEquals(7, query("/ ")); } @Test - public void uriFragmentNotation() { + void uriFragmentNotation() { assertEquals("[\"bar\",\"baz\"]", query("#/foo").toString()); } @Test - public void uriFragmentNotationRoot() { + void uriFragmentNotationRoot() { assertTrue(new JSONObject(EXPECTED_COMPLETE_DOCUMENT).similar(query("#"))); } @Test - public void uriFragmentPercentHandling() { + void uriFragmentPercentHandling() { assertEquals(2, query("#/c%25d")); assertEquals(3, query("#/e%5Ef")); assertEquals(4, query("#/g%7Ch")); @@ -142,23 +144,29 @@ public void uriFragmentPercentHandling() { } @SuppressWarnings("unused") - @Test(expected = IllegalArgumentException.class) - public void syntaxError() { - new JSONPointer("key"); + @Test + void syntaxError() { + assertThrows(IllegalArgumentException.class, () -> { + new JSONPointer("key"); + }); } - @Test(expected = JSONPointerException.class) - public void arrayIndexFailure() { - query("/foo/2"); + @Test + void arrayIndexFailure() { + assertThrows(JSONPointerException.class, () -> { + query("/foo/2"); + }); } - @Test(expected = JSONPointerException.class) - public void primitiveFailure() { - query("/obj/key/failure"); + @Test + void primitiveFailure() { + assertThrows(JSONPointerException.class, () -> { + query("/obj/key/failure"); + }); } - + @Test - public void builderTest() { + void builderTest() { JSONPointer pointer = JSONPointer.builder() .append("obj") .append("other~key").append("another/key") @@ -166,14 +174,16 @@ public void builderTest() { .build(); assertEquals("val", pointer.queryFrom(document)); } - - @Test(expected = NullPointerException.class) - public void nullToken() { - JSONPointer.builder().append(null); + + @Test + void nullToken() { + assertThrows(NullPointerException.class, () -> { + JSONPointer.builder().append(null); + }); } - + @Test - public void toStringEscaping() { + void toStringEscaping() { JSONPointer pointer = JSONPointer.builder() .append("obj") .append("other~key").append("another/key") @@ -182,22 +192,22 @@ public void toStringEscaping() { .build(); assertEquals("/obj/other~0key/another~1key/\"/0", pointer.toString()); } - + @Test - public void emptyPointerToString() { + void emptyPointerToString() { assertEquals("", new JSONPointer("").toString()); } - + @Test - public void toURIFragment() { + void toURIFragment() { assertEquals("#/c%25d", new JSONPointer("/c%d").toURIFragment()); assertEquals("#/e%5Ef", new JSONPointer("/e^f").toURIFragment()); assertEquals("#/g%7Ch", new JSONPointer("/g|h").toURIFragment()); assertEquals("#/m%7En", new JSONPointer("/m~n").toURIFragment()); } - + @Test - public void tokenListIsCopiedInConstructor() { + void tokenListIsCopiedInConstructor() { JSONPointer.Builder b = JSONPointer.builder().append("key1"); JSONPointer jp1 = b.build(); b.append("key2"); @@ -211,7 +221,7 @@ public void tokenListIsCopiedInConstructor() { * Coverage for JSONObject query(String) */ @Test - public void queryFromJSONObject() { + void queryFromJSONObject() { String str = "{"+ "\"stringKey\":\"hello world!\","+ "\"arrayKey\":[0,1,2],"+ @@ -222,18 +232,16 @@ public void queryFromJSONObject() { "}"; JSONObject jsonObject = new JSONObject(str); Object obj = jsonObject.query("/stringKey"); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + assertEquals("hello world!", obj, "Expected 'hello world!'"); obj = jsonObject.query("/arrayKey/1"); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + assertEquals(Integer.valueOf(1), obj, "Expected 1"); obj = jsonObject.query("/objectKey/b"); - assertTrue("Expected bVal", "bVal".equals(obj)); + assertEquals("bVal", obj, "Expected bVal"); try { obj = jsonObject.query("/a/b/c"); - assertTrue("Expected JSONPointerException", false); + assertTrue(false, "Expected JSONPointerException"); } catch (JSONPointerException e) { - assertTrue("Expected bad key/value exception", - "value [null] is not an array or object therefore its key b cannot be resolved". - equals(e.getMessage())); + assertEquals("value [null] is not an array or object therefore its key b cannot be resolved", e.getMessage(), "Expected bad key/value exception"); } } @@ -241,7 +249,7 @@ public void queryFromJSONObject() { * Coverage for JSONObject query(JSONPointer) */ @Test - public void queryFromJSONObjectUsingPointer() { + void queryFromJSONObjectUsingPointer() { String str = "{"+ "\"stringKey\":\"hello world!\","+ "\"arrayKey\":[0,1,2],"+ @@ -252,18 +260,16 @@ public void queryFromJSONObjectUsingPointer() { "}"; JSONObject jsonObject = new JSONObject(str); Object obj = jsonObject.query(new JSONPointer("/stringKey")); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + assertEquals("hello world!", obj, "Expected 'hello world!'"); obj = jsonObject.query(new JSONPointer("/arrayKey/1")); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + assertEquals(Integer.valueOf(1), obj, "Expected 1"); obj = jsonObject.query(new JSONPointer("/objectKey/b")); - assertTrue("Expected bVal", "bVal".equals(obj)); + assertEquals("bVal", obj, "Expected bVal"); try { obj = jsonObject.query(new JSONPointer("/a/b/c")); - assertTrue("Expected JSONPointerException", false); + assertTrue(false, "Expected JSONPointerException"); } catch (JSONPointerException e) { - assertTrue("Expected bad key/value exception", - "value [null] is not an array or object therefore its key b cannot be resolved". - equals(e.getMessage())); + assertEquals("value [null] is not an array or object therefore its key b cannot be resolved", e.getMessage(), "Expected bad key/value exception"); } } @@ -271,7 +277,7 @@ public void queryFromJSONObjectUsingPointer() { * Coverage for JSONObject optQuery(JSONPointer) */ @Test - public void optQueryFromJSONObjectUsingPointer() { + void optQueryFromJSONObjectUsingPointer() { String str = "{"+ "\"stringKey\":\"hello world!\","+ "\"arrayKey\":[0,1,2],"+ @@ -282,20 +288,20 @@ public void optQueryFromJSONObjectUsingPointer() { "}"; JSONObject jsonObject = new JSONObject(str); Object obj = jsonObject.optQuery(new JSONPointer("/stringKey")); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + assertEquals("hello world!", obj, "Expected 'hello world!'"); obj = jsonObject.optQuery(new JSONPointer("/arrayKey/1")); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + assertEquals(Integer.valueOf(1), obj, "Expected 1"); obj = jsonObject.optQuery(new JSONPointer("/objectKey/b")); - assertTrue("Expected bVal", "bVal".equals(obj)); + assertEquals("bVal", obj, "Expected bVal"); obj = jsonObject.optQuery(new JSONPointer("/a/b/c")); - assertTrue("Expected null", obj == null); + assertTrue(obj == null, "Expected null"); } - + /** * Coverage for JSONArray query(String) */ @Test - public void queryFromJSONArray() { + void queryFromJSONArray() { String str = "["+ "\"hello world!\","+ "[0,1,2],"+ @@ -306,17 +312,16 @@ public void queryFromJSONArray() { "]"; JSONArray jsonArray = new JSONArray(str); Object obj = jsonArray.query("/0"); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + assertEquals("hello world!", obj, "Expected 'hello world!'"); obj = jsonArray.query("/1/1"); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + assertEquals(Integer.valueOf(1), obj, "Expected 1"); obj = jsonArray.query("/2/b"); - assertTrue("Expected bVal", "bVal".equals(obj)); + assertEquals("bVal", obj, "Expected bVal"); try { obj = jsonArray.query("/a/b/c"); - assertTrue("Expected JSONPointerException", false); + assertTrue(false, "Expected JSONPointerException"); } catch (JSONPointerException e) { - assertTrue("Expected bad index exception", - "a is not an array index".equals(e.getMessage())); + assertEquals("a is not an array index", e.getMessage(), "Expected bad index exception"); } } @@ -324,7 +329,7 @@ public void queryFromJSONArray() { * Coverage for JSONArray query(JSONPointer) */ @Test - public void queryFromJSONArrayUsingPointer() { + void queryFromJSONArrayUsingPointer() { String str = "["+ "\"hello world!\","+ "[0,1,2],"+ @@ -335,17 +340,16 @@ public void queryFromJSONArrayUsingPointer() { "]"; JSONArray jsonArray = new JSONArray(str); Object obj = jsonArray.query(new JSONPointer("/0")); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + assertEquals("hello world!", obj, "Expected 'hello world!'"); obj = jsonArray.query(new JSONPointer("/1/1")); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + assertEquals(Integer.valueOf(1), obj, "Expected 1"); obj = jsonArray.query(new JSONPointer("/2/b")); - assertTrue("Expected bVal", "bVal".equals(obj)); + assertEquals("bVal", obj, "Expected bVal"); try { obj = jsonArray.query(new JSONPointer("/a/b/c")); - assertTrue("Expected JSONPointerException", false); + assertTrue(false, "Expected JSONPointerException"); } catch (JSONPointerException e) { - assertTrue("Expected bad index exception", - "a is not an array index".equals(e.getMessage())); + assertEquals("a is not an array index", e.getMessage(), "Expected bad index exception"); } } @@ -353,7 +357,7 @@ public void queryFromJSONArrayUsingPointer() { * Coverage for JSONArray optQuery(JSONPointer) */ @Test - public void optQueryFromJSONArrayUsingPointer() { + void optQueryFromJSONArrayUsingPointer() { String str = "["+ "\"hello world!\","+ "[0,1,2],"+ @@ -364,15 +368,15 @@ public void optQueryFromJSONArrayUsingPointer() { "]"; JSONArray jsonArray = new JSONArray(str); Object obj = jsonArray.optQuery(new JSONPointer("/0")); - assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); + assertEquals("hello world!", obj, "Expected 'hello world!'"); obj = jsonArray.optQuery(new JSONPointer("/1/1")); - assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); + assertEquals(Integer.valueOf(1), obj, "Expected 1"); obj = jsonArray.optQuery(new JSONPointer("/2/b")); - assertTrue("Expected bVal", "bVal".equals(obj)); + assertEquals("bVal", obj, "Expected bVal"); obj = jsonArray.optQuery(new JSONPointer("/a/b/c")); - assertTrue("Expected null", obj == null); + assertTrue(obj == null, "Expected null"); } - + /** * When creating a jsonObject we need to parse escaped characters "\\\\" * --> it's the string representation of "\\", so when query'ing via the JSONPointer @@ -380,7 +384,7 @@ public void optQueryFromJSONArrayUsingPointer() { * */ @Test - public void queryFromJSONObjectUsingPointer0() { + void queryFromJSONObjectUsingPointer0() { String str = "{"+ "\"string\\\\\\\\Key\":\"hello world!\","+ diff --git a/src/test/java/org/json/junit/JSONStringTest.java b/src/test/java/org/json/junit/JSONStringTest.java index b4fee3eb7..e915c005f 100644 --- a/src/test/java/org/json/junit/JSONStringTest.java +++ b/src/test/java/org/json/junit/JSONStringTest.java @@ -4,19 +4,19 @@ Public Domain. */ -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.io.StringWriter; import java.util.*; import org.json.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests for JSONString implementations, and the difference between * {@link JSONObject#valueToString} and {@link JSONObject#writeValue}. */ -public class JSONStringTest { +class JSONStringTest { /** * This tests the JSONObject.writeValue() method. We can't test directly @@ -25,14 +25,14 @@ public class JSONStringTest { * writeValue(). */ @Test - public void writeValues() throws Exception { + void writeValues() throws Exception { JSONArray jsonArray = new JSONArray(); jsonArray.put((Object)null); StringWriter writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[null]".equals(output)); + assertEquals("[null]", output, "String values should be equal"); jsonArray = new JSONArray(); jsonArray.put(JSONObject.NULL); @@ -43,7 +43,7 @@ public void writeValues() throws Exception { writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[null]".equals(output)); + assertEquals("[null]", output, "String values should be equal"); jsonArray = new JSONArray(); jsonArray.put(new JSONObject()); @@ -54,7 +54,7 @@ public void writeValues() throws Exception { writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[{}]".equals(output)); + assertEquals("[{}]", output, "String values should be equal"); jsonArray = new JSONArray(); jsonArray.put(new JSONArray()); @@ -65,7 +65,7 @@ public void writeValues() throws Exception { writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[[]]".equals(output)); + assertEquals("[[]]", output, "String values should be equal"); jsonArray = new JSONArray(); Map singleMap = Collections.singletonMap("key1", "value1"); @@ -77,7 +77,7 @@ public void writeValues() throws Exception { writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[{\"key1\":\"value1\"}]".equals(output)); + assertEquals("[{\"key1\":\"value1\"}]", output, "String values should be equal"); jsonArray = new JSONArray(); List singleList = Collections.singletonList("entry1"); @@ -89,7 +89,7 @@ public void writeValues() throws Exception { writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[[\"entry1\"]]".equals(output)); + assertEquals("[[\"entry1\"]]", output, "String values should be equal"); jsonArray = new JSONArray(); int[] intArray = new int[] { 1, 2, 3 }; @@ -101,7 +101,7 @@ public void writeValues() throws Exception { writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[[1,2,3]]".equals(output)); + assertEquals("[[1,2,3]]", output, "String values should be equal"); jsonArray = new JSONArray(); jsonArray.put(24); @@ -112,7 +112,7 @@ public void writeValues() throws Exception { writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[24]".equals(output)); + assertEquals("[24]", output, "String values should be equal"); jsonArray = new JSONArray(); jsonArray.put("string value"); @@ -123,7 +123,7 @@ public void writeValues() throws Exception { writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[\"string value\"]".equals(output)); + assertEquals("[\"string value\"]", output, "String values should be equal"); jsonArray = new JSONArray(); jsonArray.put(true); @@ -134,7 +134,7 @@ public void writeValues() throws Exception { writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[true]".equals(output)); + assertEquals("[true]", output, "String values should be equal"); } finally { writer.close(); } @@ -147,40 +147,40 @@ public void writeValues() throws Exception { */ @SuppressWarnings("boxing") @Test - public void valuesToString() throws Exception { + void valuesToString() throws Exception { String output = JSONObject.valueToString(null); - assertTrue("String values should be equal", "null".equals(output)); + assertEquals("null", output, "String values should be equal"); output = JSONObject.valueToString(JSONObject.NULL); - assertTrue("String values should be equal", "null".equals(output)); + assertEquals("null", output, "String values should be equal"); output = JSONObject.valueToString(new JSONObject()); - assertTrue("String values should be equal", "{}".equals(output)); + assertEquals("{}", output, "String values should be equal"); output = JSONObject.valueToString(new JSONArray()); - assertTrue("String values should be equal", "[]".equals(output)); + assertEquals("[]", output, "String values should be equal"); Map singleMap = Collections.singletonMap("key1", "value1"); output = JSONObject.valueToString(singleMap); - assertTrue("String values should be equal", "{\"key1\":\"value1\"}".equals(output)); + assertEquals("{\"key1\":\"value1\"}", output, "String values should be equal"); List singleList = Collections.singletonList("entry1"); output = JSONObject.valueToString(singleList); - assertTrue("String values should be equal", "[\"entry1\"]".equals(output)); + assertEquals("[\"entry1\"]", output, "String values should be equal"); int[] intArray = new int[] { 1, 2, 3 }; output = JSONObject.valueToString(intArray); - assertTrue("String values should be equal", "[1,2,3]".equals(output)); + assertEquals("[1,2,3]", output, "String values should be equal"); output = JSONObject.valueToString(24); - assertTrue("String values should be equal", "24".equals(output)); + assertEquals("24", output, "String values should be equal"); output = JSONObject.valueToString("string value"); - assertTrue("String values should be equal", "\"string value\"".equals(output)); + assertEquals("\"string value\"", output, "String values should be equal"); output = JSONObject.valueToString(true); - assertTrue("String values should be equal", "true".equals(output)); + assertEquals("true", output, "String values should be equal"); } @@ -189,7 +189,7 @@ public void valuesToString() throws Exception { * This is the usual case. */ @Test - public void testJSONStringValue() throws Exception { + void jSONStringValue() throws Exception { JSONStringValue jsonString = new JSONStringValue(); JSONArray jsonArray = new JSONArray(); @@ -198,10 +198,10 @@ public void testJSONStringValue() throws Exception { StringWriter writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[\"the JSON string value\"]".equals(output)); + assertEquals("[\"the JSON string value\"]", output, "String values should be equal"); output = JSONObject.valueToString(jsonString); - assertTrue("String values should be equal", "\"the JSON string value\"".equals(output)); + assertEquals("\"the JSON string value\"", output, "String values should be equal"); } finally { writer.close(); } @@ -212,7 +212,7 @@ public void testJSONStringValue() throws Exception { * use the object's toString() method. In the other, throw a JSONException. */ @Test - public void testJSONNullStringValue() throws Exception { + void jSONNullStringValue() throws Exception { JSONNullStringValue jsonString = new JSONNullStringValue(); JSONArray jsonArray = new JSONArray(); @@ -221,7 +221,7 @@ public void testJSONNullStringValue() throws Exception { StringWriter writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[\"the toString value\"]".equals(output)); + assertEquals("[\"the toString value\"]", output, "String values should be equal"); // The only different between writeValue() and valueToString(): // in this case, valueToString throws a JSONException @@ -229,8 +229,8 @@ public void testJSONNullStringValue() throws Exception { output = JSONObject.valueToString(jsonString); fail("Expected an exception, got a String value"); } catch (Exception e) { - assertTrue("Expected JSONException", e instanceof JSONException); - assertTrue("Exception message does not match", "Bad value from toJSONString: null".equals(e.getMessage())); + assertTrue(e instanceof JSONException, "Expected JSONException"); + assertEquals("Bad value from toJSONString: null", e.getMessage(), "Exception message does not match"); } } finally { writer.close(); @@ -243,7 +243,7 @@ public void testJSONNullStringValue() throws Exception { * the original exception. */ @Test - public void testJSONStringExceptionValue() { + void jSONStringExceptionValue() { JSONStringExceptionValue jsonString = new JSONStringExceptionValue(); JSONArray jsonArray = new JSONArray(); @@ -267,7 +267,7 @@ public void testJSONStringExceptionValue() { JSONObject.valueToString(jsonString); fail("Expected an exception, got a String value"); } catch (JSONException e) { - assertTrue("Exception message does not match", "the exception value".equals(e.getMessage())); + assertEquals("the exception value", e.getMessage(), "Exception message does not match"); } catch(Exception e) { fail("Expected JSONException"); } @@ -278,7 +278,7 @@ public void testJSONStringExceptionValue() { * This is the usual case. */ @Test - public void testStringValue() throws Exception { + void stringValue() throws Exception { StringValue nonJsonString = new StringValue(); JSONArray jsonArray = new JSONArray(); @@ -287,10 +287,10 @@ public void testStringValue() throws Exception { StringWriter writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[\"the toString value for StringValue\"]".equals(output)); + assertEquals("[\"the toString value for StringValue\"]", output, "String values should be equal"); output = JSONObject.valueToString(nonJsonString); - assertTrue("String values should be equal", "\"the toString value for StringValue\"".equals(output)); + assertEquals("\"the toString value for StringValue\"", output, "String values should be equal"); } finally { writer.close(); } @@ -301,7 +301,7 @@ public void testStringValue() throws Exception { * Defaults to empty string. */ @Test - public void testNullStringValue() throws Exception { + void nullStringValue() throws Exception { NullStringValue nonJsonString = new NullStringValue(); JSONArray jsonArray = new JSONArray(); @@ -310,10 +310,10 @@ public void testNullStringValue() throws Exception { StringWriter writer = new StringWriter(); try { String output = jsonArray.write(writer).toString(); - assertTrue("String values should be equal", "[\"\"]".equals(output)); + assertEquals("[\"\"]", output, "String values should be equal"); output = JSONObject.valueToString(nonJsonString); - assertTrue("String values should be equal", "\"\"".equals(output)); + assertEquals("\"\"", output, "String values should be equal"); } finally { writer.close(); } diff --git a/src/test/java/org/json/junit/JSONStringerTest.java b/src/test/java/org/json/junit/JSONStringerTest.java index 0ecb9d662..bc868d31f 100644 --- a/src/test/java/org/json/junit/JSONStringerTest.java +++ b/src/test/java/org/json/junit/JSONStringerTest.java @@ -4,13 +4,13 @@ Public Domain. */ -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; import java.math.BigDecimal; import java.util.*; import org.json.*; -import org.junit.Test; +import org.junit.jupiter.api.Test; import com.jayway.jsonpath.*; @@ -18,23 +18,21 @@ /** * Tests for JSON-Java JSONStringer and JSONWriter. */ -public class JSONStringerTest { +class JSONStringerTest { /** * Object with a null key. * Expects a JSONException. */ @Test - public void nullKeyException() { + void nullKeyException() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object(); try { jsonStringer.key(null); - assertTrue("Expected an exception", false); + assertTrue(false, "Expected an exception"); } catch (JSONException e) { - assertTrue("Expected an exception message", - "Null key.". - equals(e.getMessage())); + assertEquals("Null key.", e.getMessage(), "Expected an exception message"); } } @@ -43,15 +41,13 @@ public void nullKeyException() { * Expects a JSONException. */ @Test - public void outOfSequenceException() { + void outOfSequenceException() { JSONStringer jsonStringer = new JSONStringer(); try { jsonStringer.key("hi"); - assertTrue("Expected an exception", false); + assertTrue(false, "Expected an exception"); } catch (JSONException e) { - assertTrue("Expected an exception message", - "Misplaced key.". - equals(e.getMessage())); + assertEquals("Misplaced key.", e.getMessage(), "Expected an exception message"); } } @@ -60,16 +56,14 @@ public void outOfSequenceException() { * Expects a JSONException */ @Test - public void missplacedArrayException() { + void missplacedArrayException() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object().endObject(); try { jsonStringer.array(); - assertTrue("Expected an exception", false); + assertTrue(false, "Expected an exception"); } catch (JSONException e) { - assertTrue("Expected an exception message", - "Misplaced array.". - equals(e.getMessage())); + assertEquals("Misplaced array.", e.getMessage(), "Expected an exception message"); } } @@ -78,16 +72,14 @@ public void missplacedArrayException() { * Expects a JSONException */ @Test - public void missplacedEndArrayException() { + void missplacedEndArrayException() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object(); try { jsonStringer.endArray(); - assertTrue("Expected an exception", false); + assertTrue(false, "Expected an exception"); } catch (JSONException e) { - assertTrue("Expected an exception message", - "Misplaced endArray.". - equals(e.getMessage())); + assertEquals("Misplaced endArray.", e.getMessage(), "Expected an exception message"); } } @@ -96,16 +88,14 @@ public void missplacedEndArrayException() { * Expects a JSONException */ @Test - public void missplacedEndObjectException() { + void missplacedEndObjectException() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.array(); try { jsonStringer.endObject(); - assertTrue("Expected an exception", false); + assertTrue(false, "Expected an exception"); } catch (JSONException e) { - assertTrue("Expected an exception message", - "Misplaced endObject.". - equals(e.getMessage())); + assertEquals("Misplaced endObject.", e.getMessage(), "Expected an exception message"); } } @@ -114,16 +104,14 @@ public void missplacedEndObjectException() { * Expects a JSONException. */ @Test - public void missplacedObjectException() { + void missplacedObjectException() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object().endObject(); try { jsonStringer.object(); - assertTrue("Expected an exception", false); + assertTrue(false, "Expected an exception"); } catch (JSONException e) { - assertTrue("Expected an exception message", - "Misplaced object.". - equals(e.getMessage())); + assertEquals("Misplaced object.", e.getMessage(), "Expected an exception message"); } } @@ -132,7 +120,7 @@ public void missplacedObjectException() { * Expects a JSONException */ @Test - public void exceedNestDepthException() { + void exceedNestDepthException() { try { JSONStringer s = new JSONStringer(); s.object(). @@ -216,9 +204,7 @@ public void exceedNestDepthException() { key("k").object().key("k").object().key("k").object().key("k").object().key("k").object(); fail("Expected an exception message"); } catch (JSONException e) { - assertTrue("Expected an exception message", - "Nesting too deep.". - equals(e.getMessage())); + assertEquals("Nesting too deep.", e.getMessage(), "Expected an exception message"); } } @@ -227,7 +213,7 @@ public void exceedNestDepthException() { * then convert to JSONObject */ @Test - public void simpleObjectString() { + void simpleObjectString() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object(); jsonStringer.key("trueValue").value(true); @@ -243,14 +229,14 @@ public void simpleObjectString() { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 7 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 7); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueValue"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseValue"))); - assertTrue("expected null", JSONObject.NULL.equals(jsonObject.query("/nullValue"))); - assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/stringValue"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/complexStringValue"))); - assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/intValue"))); - assertTrue("expected -23.45e67", BigDecimal.valueOf(-23.45e67).equals(jsonObject.query("/doubleValue"))); + assertEquals(7, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 7 top level items"); + assertEquals(Boolean.TRUE, jsonObject.query("/trueValue"), "expected true"); + assertEquals(Boolean.FALSE, jsonObject.query("/falseValue"), "expected false"); + assertEquals(JSONObject.NULL, jsonObject.query("/nullValue"), "expected null"); + assertEquals("hello world!", jsonObject.query("/stringValue"), "expected hello world!"); + assertEquals("h\be\tllo w\u1234orld!", jsonObject.query("/complexStringValue"), "expected h\be\tllo w\u1234orld!"); + assertEquals(Integer.valueOf(42), jsonObject.query("/intValue"), "expected 42"); + assertEquals(BigDecimal.valueOf(-23.45e67), jsonObject.query("/doubleValue"), "expected -23.45e67"); } /** @@ -258,7 +244,7 @@ public void simpleObjectString() { * then convert to JSONArray */ @Test - public void simpleArrayString() { + void simpleArrayString() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.array(); jsonStringer.value(true); @@ -273,13 +259,13 @@ public void simpleArrayString() { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonArray.toString()); - assertTrue("expected 6 top level items", ((List)(JsonPath.read(doc, "$"))).size() == 6); - assertTrue("expected true", Boolean.TRUE.equals(jsonArray.query("/0"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonArray.query("/1"))); - assertTrue("expected null", JSONObject.NULL.equals(jsonArray.query("/2"))); - assertTrue("expected hello world!", "hello world!".equals(jsonArray.query("/3"))); - assertTrue("expected 42", Integer.valueOf(42).equals(jsonArray.query("/4"))); - assertTrue("expected -23.45e67", BigDecimal.valueOf(-23.45e67).equals(jsonArray.query("/5"))); + assertEquals(6, ((List)(JsonPath.read(doc, "$"))).size(), "expected 6 top level items"); + assertEquals(Boolean.TRUE, jsonArray.query("/0"), "expected true"); + assertEquals(Boolean.FALSE, jsonArray.query("/1"), "expected false"); + assertEquals(JSONObject.NULL, jsonArray.query("/2"), "expected null"); + assertEquals("hello world!", jsonArray.query("/3"), "expected hello world!"); + assertEquals(Integer.valueOf(42), jsonArray.query("/4"), "expected 42"); + assertEquals(BigDecimal.valueOf(-23.45e67), jsonArray.query("/5"), "expected -23.45e67"); } /** @@ -288,7 +274,7 @@ public void simpleArrayString() { * returned values.. */ @Test - public void complexObjectString() { + void complexObjectString() { JSONStringer jsonStringer = new JSONStringer(); jsonStringer.object(). key("trueValue").value(true). @@ -326,32 +312,32 @@ public void complexObjectString() { // validate JSON content Object doc = Configuration.defaultConfiguration().jsonProvider().parse(jsonObject.toString()); - assertTrue("expected 8 top level items", ((Map)(JsonPath.read(doc, "$"))).size() == 8); - assertTrue("expected 4 object2 items", ((Map)(JsonPath.read(doc, "$.object2"))).size() == 4); - assertTrue("expected 5 array1 items", ((List)(JsonPath.read(doc, "$.object2.array1"))).size() == 5); - assertTrue("expected 4 array[2] items", ((Map)(JsonPath.read(doc, "$.object2.array1[2]"))).size() == 4); - assertTrue("expected 4 array1[2].array2 items", ((List)(JsonPath.read(doc, "$.object2.array1[2].array2"))).size() == 4); - assertTrue("expected true", Boolean.TRUE.equals(jsonObject.query("/trueValue"))); - assertTrue("expected false", Boolean.FALSE.equals(jsonObject.query("/falseValue"))); - assertTrue("expected null", JSONObject.NULL.equals(jsonObject.query("/nullValue"))); - assertTrue("expected hello world!", "hello world!".equals(jsonObject.query("/stringValue"))); - assertTrue("expected 42", Integer.valueOf(42).equals(jsonObject.query("/intValue"))); - assertTrue("expected -23.45e67", BigDecimal.valueOf(-23.45e67).equals(jsonObject.query("/doubleValue"))); - assertTrue("expected h\be\tllo w\u1234orld!", "h\be\tllo w\u1234orld!".equals(jsonObject.query("/complexStringValue"))); - assertTrue("expected v1", "v1".equals(jsonObject.query("/object2/k1"))); - assertTrue("expected v2", "v2".equals(jsonObject.query("/object2/k2"))); - assertTrue("expected v3", "v3".equals(jsonObject.query("/object2/k3"))); - assertTrue("expected 1", Integer.valueOf(1).equals(jsonObject.query("/object2/array1/0"))); - assertTrue("expected 2", Integer.valueOf(2).equals(jsonObject.query("/object2/array1/1"))); - assertTrue("expected v4", "v4".equals(jsonObject.query("/object2/array1/2/k4"))); - assertTrue("expected v5", "v5".equals(jsonObject.query("/object2/array1/2/k5"))); - assertTrue("expected v6", "v6".equals(jsonObject.query("/object2/array1/2/k6"))); - assertTrue("expected 5", Integer.valueOf(5).equals(jsonObject.query("/object2/array1/2/array2/0"))); - assertTrue("expected 6", Integer.valueOf(6).equals(jsonObject.query("/object2/array1/2/array2/1"))); - assertTrue("expected 7", Integer.valueOf(7).equals(jsonObject.query("/object2/array1/2/array2/2"))); - assertTrue("expected 8", Integer.valueOf(8).equals(jsonObject.query("/object2/array1/2/array2/3"))); - assertTrue("expected 3", Integer.valueOf(3).equals(jsonObject.query("/object2/array1/3"))); - assertTrue("expected 4", Integer.valueOf(4).equals(jsonObject.query("/object2/array1/4"))); + assertEquals(8, ((Map)(JsonPath.read(doc, "$"))).size(), "expected 8 top level items"); + assertEquals(4, ((Map)(JsonPath.read(doc, "$.object2"))).size(), "expected 4 object2 items"); + assertEquals(5, ((List)(JsonPath.read(doc, "$.object2.array1"))).size(), "expected 5 array1 items"); + assertEquals(4, ((Map)(JsonPath.read(doc, "$.object2.array1[2]"))).size(), "expected 4 array[2] items"); + assertEquals(4, ((List)(JsonPath.read(doc, "$.object2.array1[2].array2"))).size(), "expected 4 array1[2].array2 items"); + assertEquals(Boolean.TRUE, jsonObject.query("/trueValue"), "expected true"); + assertEquals(Boolean.FALSE, jsonObject.query("/falseValue"), "expected false"); + assertEquals(JSONObject.NULL, jsonObject.query("/nullValue"), "expected null"); + assertEquals("hello world!", jsonObject.query("/stringValue"), "expected hello world!"); + assertEquals(Integer.valueOf(42), jsonObject.query("/intValue"), "expected 42"); + assertEquals(BigDecimal.valueOf(-23.45e67), jsonObject.query("/doubleValue"), "expected -23.45e67"); + assertEquals("h\be\tllo w\u1234orld!", jsonObject.query("/complexStringValue"), "expected h\be\tllo w\u1234orld!"); + assertEquals("v1", jsonObject.query("/object2/k1"), "expected v1"); + assertEquals("v2", jsonObject.query("/object2/k2"), "expected v2"); + assertEquals("v3", jsonObject.query("/object2/k3"), "expected v3"); + assertEquals(Integer.valueOf(1), jsonObject.query("/object2/array1/0"), "expected 1"); + assertEquals(Integer.valueOf(2), jsonObject.query("/object2/array1/1"), "expected 2"); + assertEquals("v4", jsonObject.query("/object2/array1/2/k4"), "expected v4"); + assertEquals("v5", jsonObject.query("/object2/array1/2/k5"), "expected v5"); + assertEquals("v6", jsonObject.query("/object2/array1/2/k6"), "expected v6"); + assertEquals(Integer.valueOf(5), jsonObject.query("/object2/array1/2/array2/0"), "expected 5"); + assertEquals(Integer.valueOf(6), jsonObject.query("/object2/array1/2/array2/1"), "expected 6"); + assertEquals(Integer.valueOf(7), jsonObject.query("/object2/array1/2/array2/2"), "expected 7"); + assertEquals(Integer.valueOf(8), jsonObject.query("/object2/array1/2/array2/3"), "expected 8"); + assertEquals(Integer.valueOf(3), jsonObject.query("/object2/array1/3"), "expected 3"); + assertEquals(Integer.valueOf(4), jsonObject.query("/object2/array1/4"), "expected 4"); } } diff --git a/src/test/java/org/json/junit/JSONTokenerTest.java b/src/test/java/org/json/junit/JSONTokenerTest.java index 59ca6d8f6..668ae4502 100644 --- a/src/test/java/org/json/junit/JSONTokenerTest.java +++ b/src/test/java/org/json/junit/JSONTokenerTest.java @@ -4,10 +4,7 @@ Public Domain. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -20,21 +17,21 @@ import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Test specific to the {@link org.json.JSONTokener} class. * @author John Aylward * */ -public class JSONTokenerTest { +class JSONTokenerTest { /** * verify that back() fails as expected. * @throws IOException thrown if something unexpected happens. */ @Test - public void verifyBackFailureZeroIndex() throws IOException { + void verifyBackFailureZeroIndex() throws IOException { Reader reader = new StringReader("some test string"); try { final JSONTokener tokener = new JSONTokener(reader); @@ -52,12 +49,13 @@ public void verifyBackFailureZeroIndex() throws IOException { reader.close(); } } + /** * verify that back() fails as expected. * @throws IOException thrown if something unexpected happens. */ @Test - public void verifyBackFailureDoubleBack() throws IOException { + void verifyBackFailureDoubleBack() throws IOException { Reader reader = new StringReader("some test string"); try { final JSONTokener tokener = new JSONTokener(reader); @@ -76,9 +74,9 @@ public void verifyBackFailureDoubleBack() throws IOException { reader.close(); } } - + @Test - public void testValid() { + void valid() { checkValid("0",Number.class); checkValid(" 0 ",Number.class); checkValid("23",Number.class); @@ -100,9 +98,9 @@ public void testValid() { checkValid("\n\n[1,2]\n\n",JSONArray.class); checkValid("1 2", String.class); } - + @Test - public void testErrors() { + void errors() { // Check that stream can detect that a value is found after // the first one checkError(" { \"a\":1 } 4 "); @@ -171,7 +169,7 @@ private Object nextValue(String testStr) throws JSONException { } } - + /** * Tests the failure of the skipTo method with a buffered reader. Preferably * we'd like this not to fail but at this time we don't have a good recovery. @@ -179,7 +177,7 @@ private Object nextValue(String testStr) throws JSONException { * @throws IOException thrown if something unexpected happens. */ @Test - public void testSkipToFailureWithBufferedReader() throws IOException { + void skipToFailureWithBufferedReader() throws IOException { final byte[] superLongBuffer = new byte[1000001]; // fill our buffer for(int i=0;i keys = jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); @@ -82,17 +81,17 @@ private static void compareActualVsExpectedObjects(Object value, */ if (!(value instanceof Number && expectedValue instanceof Number)) { // Non-Number and non-matching types - assertEquals("object types should be equal ", - expectedValue.getClass().toString(), - value.getClass().toString() + assertEquals(expectedValue.getClass().toString(), + value.getClass().toString(), + "object types should be equal " ); } /** * Same types or both Numbers, compare by toString() */ - assertEquals("values should be equal", - expectedValue.toString(), - value.toString() + assertEquals(expectedValue.toString(), + value.toString(), + "values should be equal" ); } } diff --git a/src/test/java/org/json/junit/XMLConfigurationTest.java b/src/test/java/org/json/junit/XMLConfigurationTest.java index ffdc20cd2..ee8736950 100755 --- a/src/test/java/org/json/junit/XMLConfigurationTest.java +++ b/src/test/java/org/json/junit/XMLConfigurationTest.java @@ -18,11 +18,10 @@ import org.json.JSONObject; import org.json.XML; import org.json.XMLParserConfiguration; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** @@ -33,42 +32,44 @@ public class XMLConfigurationTest { * JUnit supports temporary files and folders that are cleaned up after the test. * https://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/ */ - @Rule - public TemporaryFolder testFolder = new TemporaryFolder(); + @TempDir + public File testFolder; /** * JSONObject from a null XML string. * Expects a NullPointerException */ - @Test(expected=NullPointerException.class) - public void shouldHandleNullXML() { - String xmlStr = null; - JSONObject jsonObject = - XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS); - assertTrue("jsonObject should be empty", jsonObject.isEmpty()); + @Test + void shouldHandleNullXML() { + assertThrows(NullPointerException.class, () -> { + String xmlStr = null; + JSONObject jsonObject = + XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS); + assertTrue(jsonObject.isEmpty(), "jsonObject should be empty"); + }); } /** * Empty JSONObject from an empty XML string. */ @Test - public void shouldHandleEmptyXML() { + void shouldHandleEmptyXML() { String xmlStr = ""; JSONObject jsonObject = XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS); - assertTrue("jsonObject should be empty", jsonObject.isEmpty()); + assertTrue(jsonObject.isEmpty(), "jsonObject should be empty"); } /** * Empty JSONObject from a non-XML string. */ @Test - public void shouldHandleNonXML() { + void shouldHandleNonXML() { String xmlStr = "{ \"this is\": \"not xml\"}"; JSONObject jsonObject = XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS); - assertTrue("xml string should be empty", jsonObject.isEmpty()); + assertTrue(jsonObject.isEmpty(), "xml string should be empty"); } /** @@ -76,7 +77,7 @@ public void shouldHandleNonXML() { * Expects a JSONException */ @Test - public void shouldHandleInvalidSlashInTag() { + void shouldHandleInvalidSlashInTag() { String xmlStr = "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ @@ -317,7 +318,7 @@ public void shouldHandleCommentsInXML() { * Valid XML to XML.toString() */ @Test - public void shouldHandleToString() { + void shouldHandleToString() { String xmlStr = "\n"+ "\"}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); XMLParserConfiguration config = new XMLParserConfiguration().withcDataTagName("altContent"); String finalStr = XML.toString(expectedJsonObject, null, config); String expectedFinalStr = ">"; - assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr.equals(finalStr)); + assertEquals(expectedFinalStr, finalStr, "Should handle expectedFinal: [" + expectedStr + "] final: [" + + finalStr + "]"); } /** @@ -370,7 +371,7 @@ public void shouldHandleContentNoArraytoString() { * TODO: This is probably an error in how the 'content' keyword is used. */ @Test - public void shouldHandleContentArraytoString() { + void shouldHandleContentArraytoString() { String expectedStr = "{\"addresses\":{\"altContent\":[1, 2, 3]}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); @@ -379,8 +380,8 @@ public void shouldHandleContentArraytoString() { String expectedFinalStr = ""+ "1\n2\n3"+ ""; - assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr.equals(finalStr)); + assertEquals(expectedFinalStr, finalStr, "Should handle expectedFinal: [" + expectedStr + "] final: [" + + finalStr + "]"); } /** @@ -388,7 +389,7 @@ public void shouldHandleContentArraytoString() { * XML.toString() should result in valid XML. */ @Test - public void shouldHandleArraytoString() { + void shouldHandleArraytoString() { String expectedStr = "{\"addresses\":{"+ "\"something\":[1, 2, 3]}}"; @@ -398,15 +399,15 @@ public void shouldHandleArraytoString() { String expectedFinalStr = ""+ "123"+ ""; - assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr.equals(finalStr)); + assertEquals(expectedFinalStr, finalStr, "Should handle expectedFinal: [" + expectedStr + "] final: [" + + finalStr + "]"); } - + /** * Tests that the XML output for empty arrays is consistent. */ @Test - public void shouldHandleEmptyArray(){ + void shouldHandleEmptyArray(){ final JSONObject jo1 = new JSONObject(); jo1.put("array",new Object[]{}); final JSONObject jo2 = new JSONObject(); @@ -415,17 +416,17 @@ public void shouldHandleEmptyArray(){ final String expected = ""; String output1 = XML.toString(jo1, "jo", XMLParserConfiguration.KEEP_STRINGS); - assertEquals("Expected an empty root tag", expected, output1); + assertEquals(expected, output1, "Expected an empty root tag"); String output2 = XML.toString(jo2, "jo", XMLParserConfiguration.KEEP_STRINGS); - assertEquals("Expected an empty root tag", expected, output2); + assertEquals(expected, output2, "Expected an empty root tag"); } - + /** * Tests that the XML output for arrays is consistent when an internal array is empty. */ @Test - public void shouldHandleEmptyMultiArray(){ + void shouldHandleEmptyMultiArray(){ final JSONObject jo1 = new JSONObject(); jo1.put("arr",new Object[]{"One", new String[]{}, "Four"}); final JSONObject jo2 = new JSONObject(); @@ -434,18 +435,18 @@ public void shouldHandleEmptyMultiArray(){ final String expected = "OneFour"; String output1 = XML.toString(jo1, "jo", XMLParserConfiguration.KEEP_STRINGS); - assertEquals("Expected a matching array", expected, output1); + assertEquals(expected, output1, "Expected a matching array"); String output2 = XML.toString(jo2, "jo", XMLParserConfiguration.KEEP_STRINGS); - assertEquals("Expected a matching array", expected, output2); + assertEquals(expected, output2, "Expected a matching array"); } - + /** * Tests that the XML output for arrays is consistent when arrays are not empty. */ @Test - public void shouldHandleNonEmptyArray(){ + void shouldHandleNonEmptyArray(){ final JSONObject jo1 = new JSONObject(); jo1.put("arr",new String[]{"One", "Two", "Three"}); final JSONObject jo2 = new JSONObject(); @@ -454,17 +455,17 @@ public void shouldHandleNonEmptyArray(){ final String expected = "OneTwoThree"; String output1 = XML.toString(jo1, "jo", XMLParserConfiguration.KEEP_STRINGS); - assertEquals("Expected a non empty root tag", expected, output1); + assertEquals(expected, output1, "Expected a non empty root tag"); String output2 = XML.toString(jo2, "jo", XMLParserConfiguration.KEEP_STRINGS); - assertEquals("Expected a non empty root tag", expected, output2); + assertEquals(expected, output2, "Expected a non empty root tag"); } /** * Tests that the XML output for arrays is consistent when arrays are not empty and contain internal arrays. */ @Test - public void shouldHandleMultiArray(){ + void shouldHandleMultiArray(){ final JSONObject jo1 = new JSONObject(); jo1.put("arr",new Object[]{"One", new String[]{"Two", "Three"}, "Four"}); final JSONObject jo2 = new JSONObject(); @@ -473,10 +474,10 @@ public void shouldHandleMultiArray(){ final String expected = "OneTwoThreeFour"; String output1 = XML.toString(jo1, "jo", XMLParserConfiguration.KEEP_STRINGS); - assertEquals("Expected a matching array", expected, output1); + assertEquals(expected, output1, "Expected a matching array"); String output2 = XML.toString(jo2, "jo", XMLParserConfiguration.KEEP_STRINGS); - assertEquals("Expected a matching array", expected, output2); + assertEquals(expected, output2, "Expected a matching array"); } /** @@ -484,7 +485,7 @@ public void shouldHandleMultiArray(){ * JSONObject, then XML.toString() should result in valid XML. */ @Test - public void shouldHandleNestedArraytoString() { + void shouldHandleNestedArraytoString() { String xmlStr = "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ "\"outer\":[[1], [2], [3]]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ @@ -512,7 +513,7 @@ public void shouldHandleNestedArraytoString() { * Therefore illegal arguments should be converted to e.g. an underscore (_). */ @Test - public void shouldHandleIllegalJSONNodeNames() + void shouldHandleIllegalJSONNodeNames() { JSONObject inputJSON = new JSONObject(); inputJSON.append("123IllegalNode", "someValue1"); @@ -529,16 +530,16 @@ public void shouldHandleIllegalJSONNodeNames() */ String expected = "<123IllegalNode>someValue1someValue2"; - assertEquals("Length", expected.length(), result.length()); - assertTrue("123IllegalNode", result.contains("<123IllegalNode>someValue1")); - assertTrue("Illegal@node", result.contains("someValue2")); + assertEquals(expected.length(), result.length(), "Length"); + assertTrue(result.contains("<123IllegalNode>someValue1"), "123IllegalNode"); + assertTrue(result.contains("someValue2"), "Illegal@node"); } /** * JSONObject with NULL value, to XML.toString() */ @Test - public void shouldHandleNullNodeValue() + void shouldHandleNullNodeValue() { JSONObject inputJSON = new JSONObject(); inputJSON.put("nullValue", JSONObject.NULL); @@ -555,7 +556,7 @@ public void shouldHandleNullNodeValue() } @Test - public void shouldHandleEmptyNodeValue() + void shouldHandleEmptyNodeValue() { JSONObject inputJSON = new JSONObject(); inputJSON.put("Emptyness", ""); @@ -568,7 +569,7 @@ public void shouldHandleEmptyNodeValue() } @Test - public void shouldKeepConfigurationIntactAndUpdateCloseEmptyTagChoice() + void shouldKeepConfigurationIntactAndUpdateCloseEmptyTagChoice() { XMLParserConfiguration keepStrings = XMLParserConfiguration.KEEP_STRINGS; XMLParserConfiguration keepStringsAndCloseEmptyTag = keepStrings.withCloseEmptyTag(true); @@ -589,7 +590,7 @@ public void shouldKeepConfigurationIntactAndUpdateCloseEmptyTagChoice() * Investigate exactly how the "content" keyword works */ @Test - public void contentOperations() { + void contentOperations() { /* * When a standalone 0) then return]]>"; JSONObject jsonObject = XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS); - assertTrue("1. 3 items", 3 == jsonObject.length()); - assertTrue("1. empty tag1", "".equals(jsonObject.get("tag1"))); - assertTrue("1. empty tag2", "".equals(jsonObject.get("tag2"))); - assertTrue("1. content found", "if (a < b && a > 0) then return".equals(jsonObject.get("content"))); + assertEquals(3, jsonObject.length(), "1. 3 items"); + assertEquals("", jsonObject.get("tag1"), "1. empty tag1"); + assertEquals("", jsonObject.get("tag2"), "1. empty tag2"); + assertEquals("if (a < b && a > 0) then return", jsonObject.get("content"), "1. content found"); // multiple consecutive standalone cdatas are accumulated into an array xmlStr = " 0) then return]]>"; @@ -608,14 +609,14 @@ public void contentOperations() { new XMLParserConfiguration() .withKeepStrings(true) .withcDataTagName("altContent")); - assertTrue("2. 3 items", 3 == jsonObject.length()); - assertTrue("2. empty tag1", "".equals(jsonObject.get("tag1"))); - assertTrue("2. empty tag2", "".equals(jsonObject.get("tag2"))); - assertTrue("2. content array found", jsonObject.get("altContent") instanceof JSONArray); + assertEquals(3, jsonObject.length(), "2. 3 items"); + assertEquals("", jsonObject.get("tag1"), "2. empty tag1"); + assertEquals("", jsonObject.get("tag2"), "2. empty tag2"); + assertTrue(jsonObject.get("altContent") instanceof JSONArray, "2. content array found"); JSONArray jsonArray = jsonObject.getJSONArray("altContent"); - assertTrue("2. array size", jsonArray.length() == 2); - assertTrue("2. content array entry 0", "if (a < b && a > 0) then return".equals(jsonArray.get(0))); - assertTrue("2. content array entry 1", "here is another cdata".equals(jsonArray.get(1))); + assertEquals(2, jsonArray.length(), "2. array size"); + assertEquals("if (a < b && a > 0) then return", jsonArray.get(0), "2. content array entry 0"); + assertEquals("here is another cdata", jsonArray.get(1), "2. content array entry 1"); /* * text content is accumulated in a "content" inside a local JSONObject. @@ -627,8 +628,8 @@ public void contentOperations() { new XMLParserConfiguration() .withKeepStrings(true) .withcDataTagName("altContent")); - assertTrue("3. 2 items", 1 == jsonObject.length()); - assertTrue("3. value tag1", "value 1".equals(jsonObject.get("tag1"))); + assertEquals(1, jsonObject.length(), "3. 2 items"); + assertEquals("value 1", jsonObject.get("tag1"), "3. value tag1"); /* * array-style text content (multiple tags with the same name) is @@ -640,13 +641,13 @@ public void contentOperations() { new XMLParserConfiguration() .withKeepStrings(true) .withcDataTagName("altContent")); - assertTrue("4. 1 item", 1 == jsonObject.length()); - assertTrue("4. content array found", jsonObject.get("tag1") instanceof JSONArray); + assertEquals(1, jsonObject.length(), "4. 1 item"); + assertTrue(jsonObject.get("tag1") instanceof JSONArray, "4. content array found"); jsonArray = jsonObject.getJSONArray("tag1"); - assertTrue("4. array size", jsonArray.length() == 3); - assertTrue("4. content array entry 0", "value 1".equals(jsonArray.get(0))); - assertTrue("4. content array entry 1", jsonArray.getInt(1) == 2); - assertTrue("4. content array entry 2", jsonArray.getBoolean(2) == true); + assertEquals(3, jsonArray.length(), "4. array size"); + assertEquals("value 1", jsonArray.get(0), "4. content array entry 0"); + assertEquals(2, jsonArray.getInt(1), "4. content array entry 1"); + assertTrue(jsonArray.getBoolean(2), "4. content array entry 2"); /* * Complex content is accumulated in a "content" field. For example, an element @@ -658,18 +659,18 @@ public void contentOperations() { new XMLParserConfiguration() .withKeepStrings(true) .withcDataTagName("altContent")); - assertTrue("5. 1 item", 1 == jsonObject.length()); - assertTrue("5. jsonObject found", jsonObject.get("tag1") - instanceof JSONObject); + assertEquals(1, jsonObject.length(), "5. 1 item"); + assertTrue(jsonObject.get("tag1") + instanceof JSONObject, "5. jsonObject found"); jsonObject = jsonObject.getJSONObject("tag1"); - assertTrue("5. 2 contained items", 2 == jsonObject.length()); - assertTrue("5. contained tag", "".equals(jsonObject.get("tag2"))); - assertTrue("5. contained content jsonArray found", - jsonObject.get("altContent") instanceof JSONArray); + assertEquals(2, jsonObject.length(), "5. 2 contained items"); + assertEquals("", jsonObject.get("tag2"), "5. contained tag"); + assertTrue(jsonObject.get("altContent") instanceof JSONArray, + "5. contained content jsonArray found"); jsonArray = jsonObject.getJSONArray("altContent"); - assertTrue("5. array size", jsonArray.length() == 2); - assertTrue("5. content array entry 0", "val1".equals(jsonArray.get(0))); - assertTrue("5. content array entry 1", "val2".equals(jsonArray.get(1))); + assertEquals(2, jsonArray.length(), "5. array size"); + assertEquals("val1", jsonArray.get(0), "5. content array entry 0"); + assertEquals("val2", jsonArray.get(1), "5. content array entry 1"); /* * If there is only 1 complex text content, then it is accumulated in a @@ -680,12 +681,11 @@ public void contentOperations() { new XMLParserConfiguration() .withKeepStrings(true) .withcDataTagName("altContent")); - assertTrue("6. 1 item", 1 == jsonObject.length()); - assertTrue("6. jsonObject found", jsonObject.get("tag1") instanceof JSONObject); + assertEquals(1, jsonObject.length(), "6. 1 item"); + assertTrue(jsonObject.get("tag1") instanceof JSONObject, "6. jsonObject found"); jsonObject = jsonObject.getJSONObject("tag1"); - assertTrue("6. contained content found", - "val1".equals(jsonObject.get("altContent"))); - assertTrue("6. contained tag2", "".equals(jsonObject.get("tag2"))); + assertEquals("val1", jsonObject.get("altContent"), "6. contained content found"); + assertEquals("", jsonObject.get("tag2"), "6. contained tag2"); /* * In this corner case, the content sibling happens to have key=content @@ -697,17 +697,17 @@ public void contentOperations() { new XMLParserConfiguration() .withKeepStrings(true) .withcDataTagName("altContent")); - assertTrue("7. 1 item", 1 == jsonObject.length()); - assertTrue("7. jsonArray found", - jsonObject.get("tag1") instanceof JSONArray); + assertEquals(1, jsonObject.length(), "7. 1 item"); + assertTrue(jsonObject.get("tag1") instanceof JSONArray, + "7. jsonArray found"); jsonArray = jsonObject.getJSONArray("tag1"); - assertTrue("array size 1", jsonArray.length() == 1); - assertTrue("7. contained array found", jsonArray.get(0) - instanceof JSONArray); + assertEquals(1, jsonArray.length(), "array size 1"); + assertTrue(jsonArray.get(0) + instanceof JSONArray, "7. contained array found"); jsonArray = jsonArray.getJSONArray(0); - assertTrue("7. inner array size 2", jsonArray.length() == 2); - assertTrue("7. inner array item 0", "val1".equals(jsonArray.get(0))); - assertTrue("7. inner array item 1", "".equals(jsonArray.get(1))); + assertEquals(2, jsonArray.length(), "7. inner array size 2"); + assertEquals("val1", jsonArray.get(0), "7. inner array item 0"); + assertEquals("", jsonArray.get(1), "7. inner array item 1"); /* * Confirm behavior of original issue @@ -752,14 +752,14 @@ public void contentOperations() { * * */ - assertTrue("nothing to test here, see comment on created XML, above", true); + assertTrue(true, "nothing to test here, see comment on created XML, above"); } /** * JSON string lost leading zero and converted "True" to true. */ @Test - public void testToJSONArray_jsonOutput() { + void toJSONArray_jsonOutput() { final String originalXml = "011000True"; final JSONObject expected = new JSONObject("{\"root\":{\"item\":{\"id\":1},\"id\":[1,1,0,0],\"title\":true}}"); final JSONObject actualJsonOutput = XML.toJSONObject(originalXml, @@ -771,7 +771,7 @@ public void testToJSONArray_jsonOutput() { * JSON string cannot be reverted to original xml. */ @Test - public void testToJSONArray_reversibility() { + void toJSONArray_reversibility() { final String originalXml = "011000True"; XMLParserConfiguration config = new XMLParserConfiguration().withKeepStrings(false); final String revertedXml = @@ -784,7 +784,7 @@ public void testToJSONArray_reversibility() { * test passes when using the new method toJsonArray. */ @Test - public void testToJsonXML() { + void toJsonXML() { final String originalXml = "011000True"; final JSONObject expected = new JSONObject("{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\"],\"title\":\"True\"}}"); @@ -796,17 +796,17 @@ public void testToJsonXML() { // this reversal isn't exactly the same. use JSONML for an exact reversal final String expectedReverseXml = "01011000True"; - assertEquals("length",expectedReverseXml.length(), reverseXml.length()); - assertTrue("array contents", reverseXml.contains("011000")); - assertTrue("item contents", reverseXml.contains("01")); - assertTrue("title contents", reverseXml.contains("True")); + assertEquals(expectedReverseXml.length(), reverseXml.length(), "length"); + assertTrue(reverseXml.contains("011000"), "array contents"); + assertTrue(reverseXml.contains("01"), "item contents"); + assertTrue(reverseXml.contains("True"), "title contents"); } - + /** * test to validate certain conditions of XML unescaping. */ @Test - public void testUnescape() { + void unescape() { assertEquals("{\"xml\":\"Can cope <;\"}", XML.toJSONObject("Can cope <; ", XMLParserConfiguration.KEEP_STRINGS).toString()); @@ -845,7 +845,7 @@ public void testUnescape() { * Confirm XMLParserConfiguration functionality */ @Test - public void testConfig() { + void config() { /** * 1st param is whether to keep the raw string, or call * XML.stringToValue(), which may convert the token to @@ -879,8 +879,8 @@ public void testConfig() { .withcDataTagName("altContent"); JSONObject jsonObject = XML.toJSONObject(xmlStr, config); // num is parsed as a string - assertEquals(jsonObject.getJSONObject("addresses"). - getJSONObject("address").getString("num"), "1"); + assertEquals("1", jsonObject.getJSONObject("addresses"). + getJSONObject("address").getString("num")); // complex content is collected in an 'altContent' array JSONArray jsonArray = jsonObject.getJSONObject("addresses"). getJSONObject("address").getJSONArray("altContent"); @@ -892,8 +892,8 @@ public void testConfig() { jsonObject = XML.toJSONObject(xmlStr, XMLParserConfiguration.KEEP_STRINGS); // num is parsed as a string - assertEquals(jsonObject.getJSONObject("addresses"). - getJSONObject("address").getString("num"), "1"); + assertEquals("1", jsonObject.getJSONObject("addresses"). + getJSONObject("address").getString("num")); // complex content is collected in an 'content' array jsonArray = jsonObject.getJSONObject("addresses"). getJSONObject("address").getJSONArray("content"); @@ -904,8 +904,8 @@ public void testConfig() { config = new XMLParserConfiguration().withcDataTagName("altContent"); jsonObject = XML.toJSONObject(xmlStr, config); // num is parsed as a number - assertEquals(jsonObject.getJSONObject("addresses"). - getJSONObject("address").getInt("num"), 1); + assertEquals(1, jsonObject.getJSONObject("addresses"). + getJSONObject("address").getInt("num")); // complex content is collected in an 'altContent' array jsonArray = jsonObject.getJSONObject("addresses"). getJSONObject("address").getJSONArray("altContent"); @@ -918,7 +918,7 @@ public void testConfig() { * Test forceList parameter */ @Test - public void testSimpleForceList() { + void simpleForceList() { String xmlStr = "\n"+ "\n"+ @@ -941,8 +941,9 @@ public void testSimpleForceList() { Util.compareActualVsExpectedJsonObjects(jsonObject, expetedJsonObject); } + @Test - public void testLongForceList() { + void longForceList() { String xmlStr = ""+ ""+ @@ -983,8 +984,9 @@ public void testLongForceList() { Util.compareActualVsExpectedJsonObjects(jsonObject, expetedJsonObject); } + @Test - public void testMultipleTagForceList() { + void multipleTagForceList() { String xmlStr = "\n"+ "
\n"+ @@ -1022,8 +1024,9 @@ public void testMultipleTagForceList() { Util.compareActualVsExpectedJsonObjects(jsonObject, expetedJsonObject); } + @Test - public void testEmptyForceList() { + void emptyForceList() { String xmlStr = ""; @@ -1041,8 +1044,9 @@ public void testEmptyForceList() { Util.compareActualVsExpectedJsonObjects(jsonObject, expetedJsonObject); } + @Test - public void testContentForceList() { + void contentForceList() { String xmlStr = "Baker Street"; @@ -1060,8 +1064,9 @@ public void testContentForceList() { Util.compareActualVsExpectedJsonObjects(jsonObject, expetedJsonObject); } + @Test - public void testEmptyTagForceList() { + void emptyTagForceList() { String xmlStr = ""; @@ -1081,26 +1086,26 @@ public void testEmptyTagForceList() { } @Test - public void testMaxNestingDepthIsSet() { + void maxNestingDepthIsSet() { XMLParserConfiguration xmlParserConfiguration = XMLParserConfiguration.ORIGINAL; - assertEquals(xmlParserConfiguration.getMaxNestingDepth(), XMLParserConfiguration.DEFAULT_MAXIMUM_NESTING_DEPTH); + assertEquals(XMLParserConfiguration.DEFAULT_MAXIMUM_NESTING_DEPTH, xmlParserConfiguration.getMaxNestingDepth()); xmlParserConfiguration = xmlParserConfiguration.withMaxNestingDepth(42); - assertEquals(xmlParserConfiguration.getMaxNestingDepth(), 42); + assertEquals(42, xmlParserConfiguration.getMaxNestingDepth()); xmlParserConfiguration = xmlParserConfiguration.withMaxNestingDepth(0); - assertEquals(xmlParserConfiguration.getMaxNestingDepth(), 0); + assertEquals(0, xmlParserConfiguration.getMaxNestingDepth()); xmlParserConfiguration = xmlParserConfiguration.withMaxNestingDepth(-31415926); - assertEquals(xmlParserConfiguration.getMaxNestingDepth(), XMLParserConfiguration.UNDEFINED_MAXIMUM_NESTING_DEPTH); + assertEquals(XMLParserConfiguration.UNDEFINED_MAXIMUM_NESTING_DEPTH, xmlParserConfiguration.getMaxNestingDepth()); xmlParserConfiguration = xmlParserConfiguration.withMaxNestingDepth(Integer.MIN_VALUE); - assertEquals(xmlParserConfiguration.getMaxNestingDepth(), XMLParserConfiguration.UNDEFINED_MAXIMUM_NESTING_DEPTH); + assertEquals(XMLParserConfiguration.UNDEFINED_MAXIMUM_NESTING_DEPTH, xmlParserConfiguration.getMaxNestingDepth()); } /** @@ -1137,7 +1142,7 @@ private void compareReaderToJSONObject(String xmlStr, String expectedStr, JSONObject jsonObject = XML.toJSONObject(reader, config); Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); } catch (Exception e) { - assertTrue("Reader error: " +e.getMessage(), false); + assertTrue(false, "Reader error: " +e.getMessage()); } finally { try { reader.close(); @@ -1162,7 +1167,7 @@ private void compareFileToJSONObject(String xmlStr, String expectedStr) { */ try { JSONObject expectedJsonObject = new JSONObject(expectedStr); - File tempFile = this.testFolder.newFile("fileToJSONObject.xml"); + File tempFile = File.createTempFile("fileToJSONObject.xml", null, this.testFolder); FileWriter fileWriter = new FileWriter(tempFile); try { fileWriter.write(xmlStr); @@ -1178,7 +1183,7 @@ private void compareFileToJSONObject(String xmlStr, String expectedStr) { reader.close(); } } catch (IOException e) { - assertTrue("Error: " +e.getMessage(), false); + assertTrue(false, "Error: " +e.getMessage()); } } } \ No newline at end of file diff --git a/src/test/java/org/json/junit/XMLTest.java b/src/test/java/org/json/junit/XMLTest.java index 823a06591..0f0627fc3 100644 --- a/src/test/java/org/json/junit/XMLTest.java +++ b/src/test/java/org/json/junit/XMLTest.java @@ -4,11 +4,7 @@ Public Domain. */ -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; import java.io.File; import java.io.FileReader; @@ -23,9 +19,8 @@ import java.util.Map; import org.json.*; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** @@ -37,40 +32,42 @@ public class XMLTest { * JUnit supports temporary files and folders that are cleaned up after the test. * https://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/ */ - @Rule - public TemporaryFolder testFolder = new TemporaryFolder(); + @TempDir + public File testFolder; + - /** * JSONObject from a null XML string. * Expects a NullPointerException */ - @Test(expected=NullPointerException.class) - public void shouldHandleNullXML() { - String xmlStr = null; - JSONObject jsonObject = XML.toJSONObject(xmlStr); - assertTrue("jsonObject should be empty", jsonObject.isEmpty()); + @Test + void shouldHandleNullXML() { + assertThrows(NullPointerException.class, () -> { + String xmlStr = null; + JSONObject jsonObject = XML.toJSONObject(xmlStr); + assertTrue(jsonObject.isEmpty(), "jsonObject should be empty"); + }); } /** * Empty JSONObject from an empty XML string. */ @Test - public void shouldHandleEmptyXML() { + void shouldHandleEmptyXML() { String xmlStr = ""; JSONObject jsonObject = XML.toJSONObject(xmlStr); - assertTrue("jsonObject should be empty", jsonObject.isEmpty()); + assertTrue(jsonObject.isEmpty(), "jsonObject should be empty"); } /** * Empty JSONObject from a non-XML string. */ @Test - public void shouldHandleNonXML() { + void shouldHandleNonXML() { String xmlStr = "{ \"this is\": \"not xml\"}"; JSONObject jsonObject = XML.toJSONObject(xmlStr); - assertTrue("xml string should be empty", jsonObject.isEmpty()); + assertTrue(jsonObject.isEmpty(), "xml string should be empty"); } /** @@ -78,7 +75,7 @@ public void shouldHandleNonXML() { * Expects a JSONException */ @Test - public void shouldHandleInvalidSlashInTag() { + void shouldHandleInvalidSlashInTag() { String xmlStr = "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ "\n"+ ""+ @@ -309,12 +306,12 @@ public void testXmlEscapeToJson(){ compareReaderToJSONObject(xmlStr, expectedStr); compareFileToJSONObject(xmlStr, expectedStr); } - + /** * Tests that control characters are escaped. */ @Test - public void testJsonToXmlEscape(){ + void jsonToXmlEscape(){ final String jsonSrc = "{\"amount\":\"10,00 €\"," + "\"description\":\"Ação Válida\u0085\"," + "\"xmlEntities\":\"\\\" ' & < >\"" @@ -322,26 +319,26 @@ public void testJsonToXmlEscape(){ JSONObject json = new JSONObject(jsonSrc); String xml = XML.toString(json); //test control character not existing - assertFalse("Escaping \u0085 failed. Found in XML output.", xml.contains("\u0085")); - assertTrue("Escaping \u0085 failed. Entity not found in XML output.", xml.contains("…")); + assertFalse(xml.contains("\u0085"), "Escaping \u0085 failed. Found in XML output."); + assertTrue(xml.contains("…"), "Escaping \u0085 failed. Entity not found in XML output."); // test normal unicode existing - assertTrue("Escaping € failed. Not found in XML output.", xml.contains("€")); - assertTrue("Escaping ç failed. Not found in XML output.", xml.contains("ç")); - assertTrue("Escaping ã failed. Not found in XML output.", xml.contains("ã")); - assertTrue("Escaping á failed. Not found in XML output.", xml.contains("á")); + assertTrue(xml.contains("€"), "Escaping € failed. Not found in XML output."); + assertTrue(xml.contains("ç"), "Escaping ç failed. Not found in XML output."); + assertTrue(xml.contains("ã"), "Escaping ã failed. Not found in XML output."); + assertTrue(xml.contains("á"), "Escaping á failed. Not found in XML output."); // test XML Entities converted - assertTrue("Escaping \" failed. Not found in XML output.", xml.contains(""")); - assertTrue("Escaping ' failed. Not found in XML output.", xml.contains("'")); - assertTrue("Escaping & failed. Not found in XML output.", xml.contains("&")); - assertTrue("Escaping < failed. Not found in XML output.", xml.contains("<")); - assertTrue("Escaping > failed. Not found in XML output.", xml.contains(">")); + assertTrue(xml.contains("""), "Escaping \" failed. Not found in XML output."); + assertTrue(xml.contains("'"), "Escaping ' failed. Not found in XML output."); + assertTrue(xml.contains("&"), "Escaping & failed. Not found in XML output."); + assertTrue(xml.contains("<"), "Escaping < failed. Not found in XML output."); + assertTrue(xml.contains(">"), "Escaping > failed. Not found in XML output."); } /** * Valid XML with comments to JSONObject */ @Test - public void shouldHandleCommentsInXML() { + void shouldHandleCommentsInXML() { String xmlStr = "\n"+ @@ -367,7 +364,7 @@ public void shouldHandleCommentsInXML() { * Valid XML to XML.toString() */ @Test - public void shouldHandleToString() { + void shouldHandleToString() { String xmlStr = "\n"+ "\"}}"; JSONObject expectedJsonObject = new JSONObject(expectedStr); String finalStr = XML.toString(expectedJsonObject); String expectedFinalStr = ">"; - assertEquals("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr, finalStr); + assertEquals(expectedFinalStr, finalStr, "Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]"); } /** @@ -415,7 +412,7 @@ public void shouldHandleContentNoArraytoString() { * TODO: This is probably an error in how the 'content' keyword is used. */ @Test - public void shouldHandleContentArraytoString() { + void shouldHandleContentArraytoString() { String expectedStr = "{\"addresses\":{" + "\"content\":[1, 2, 3]}}"; @@ -423,8 +420,8 @@ public void shouldHandleContentArraytoString() { String finalStr = XML.toString(expectedJsonObject); String expectedFinalStr = ""+ "1\n2\n3"; - assertEquals("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr, finalStr); + assertEquals(expectedFinalStr, finalStr, "Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]"); } /** @@ -432,7 +429,7 @@ public void shouldHandleContentArraytoString() { * XML.toString() should result in valid XML. */ @Test - public void shouldHandleArraytoString() { + void shouldHandleArraytoString() { String expectedStr = "{\"addresses\":{"+ "\"something\":[1, 2, 3]}}"; @@ -441,15 +438,15 @@ public void shouldHandleArraytoString() { String expectedFinalStr = ""+ "123"+ ""; - assertEquals("Should handle expectedFinal: ["+expectedStr+"] final: ["+ - finalStr+"]", expectedFinalStr, finalStr); + assertEquals(expectedFinalStr, finalStr, "Should handle expectedFinal: ["+expectedStr+"] final: ["+ + finalStr+"]"); } - + /** * Tests that the XML output for empty arrays is consistent. */ @Test - public void shouldHandleEmptyArray(){ + void shouldHandleEmptyArray(){ final JSONObject jo1 = new JSONObject(); jo1.put("array",new Object[]{}); final JSONObject jo2 = new JSONObject(); @@ -457,16 +454,16 @@ public void shouldHandleEmptyArray(){ final String expected = ""; String output1 = XML.toString(jo1,"jo"); - assertEquals("Expected an empty root tag", expected, output1); + assertEquals(expected, output1, "Expected an empty root tag"); String output2 = XML.toString(jo2,"jo"); - assertEquals("Expected an empty root tag", expected, output2); + assertEquals(expected, output2, "Expected an empty root tag"); } - + /** * Tests that the XML output for arrays is consistent when an internal array is empty. */ @Test - public void shouldHandleEmptyMultiArray(){ + void shouldHandleEmptyMultiArray(){ final JSONObject jo1 = new JSONObject(); jo1.put("arr",new Object[]{"One", new String[]{}, "Four"}); final JSONObject jo2 = new JSONObject(); @@ -474,16 +471,16 @@ public void shouldHandleEmptyMultiArray(){ final String expected = "OneFour"; String output1 = XML.toString(jo1,"jo"); - assertEquals("Expected a matching array", expected, output1); + assertEquals(expected, output1, "Expected a matching array"); String output2 = XML.toString(jo2,"jo"); - assertEquals("Expected a matching array", expected, output2); + assertEquals(expected, output2, "Expected a matching array"); } - + /** * Tests that the XML output for arrays is consistent when arrays are not empty. */ @Test - public void shouldHandleNonEmptyArray(){ + void shouldHandleNonEmptyArray(){ final JSONObject jo1 = new JSONObject(); jo1.put("arr",new String[]{"One", "Two", "Three"}); final JSONObject jo2 = new JSONObject(); @@ -491,16 +488,16 @@ public void shouldHandleNonEmptyArray(){ final String expected = "OneTwoThree"; String output1 = XML.toString(jo1,"jo"); - assertEquals("Expected a non empty root tag", expected, output1); + assertEquals(expected, output1, "Expected a non empty root tag"); String output2 = XML.toString(jo2,"jo"); - assertEquals("Expected a non empty root tag", expected, output2); + assertEquals(expected, output2, "Expected a non empty root tag"); } /** * Tests that the XML output for arrays is consistent when arrays are not empty and contain internal arrays. */ @Test - public void shouldHandleMultiArray(){ + void shouldHandleMultiArray(){ final JSONObject jo1 = new JSONObject(); jo1.put("arr",new Object[]{"One", new String[]{"Two", "Three"}, "Four"}); final JSONObject jo2 = new JSONObject(); @@ -508,9 +505,9 @@ public void shouldHandleMultiArray(){ final String expected = "OneTwoThreeFour"; String output1 = XML.toString(jo1,"jo"); - assertEquals("Expected a matching array", expected, output1); + assertEquals(expected, output1, "Expected a matching array"); String output2 = XML.toString(jo2,"jo"); - assertEquals("Expected a matching array", expected, output2); + assertEquals(expected, output2, "Expected a matching array"); } /** @@ -518,7 +515,7 @@ public void shouldHandleMultiArray(){ * JSONObject, then XML.toString() should result in valid XML. */ @Test - public void shouldHandleNestedArraytoString() { + void shouldHandleNestedArraytoString() { String xmlStr = "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\","+ "\"outer\":[[1], [2], [3]]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+ @@ -544,7 +541,7 @@ public void shouldHandleNestedArraytoString() { * Therefore illegal arguments should be converted to e.g. an underscore (_). */ @Test - public void shouldHandleIllegalJSONNodeNames() + void shouldHandleIllegalJSONNodeNames() { JSONObject inputJSON = new JSONObject(); inputJSON.append("123IllegalNode", "someValue1"); @@ -560,16 +557,16 @@ public void shouldHandleIllegalJSONNodeNames() */ String expected = "<123IllegalNode>someValue1someValue2"; - assertEquals("length",expected.length(), result.length()); - assertTrue("123IllegalNode",result.contains("<123IllegalNode>someValue1")); - assertTrue("Illegal@node",result.contains("someValue2")); + assertEquals(expected.length(), result.length(), "length"); + assertTrue(result.contains("<123IllegalNode>someValue1"),"123IllegalNode"); + assertTrue(result.contains("someValue2"),"Illegal@node"); } /** * JSONObject with NULL value, to XML.toString() */ @Test - public void shouldHandleNullNodeValue() + void shouldHandleNullNodeValue() { JSONObject inputJSON = new JSONObject(); inputJSON.put("nullValue", JSONObject.NULL); @@ -588,29 +585,29 @@ public void shouldHandleNullNodeValue() * Investigate exactly how the "content" keyword works */ @Test - public void contentOperations() { + void contentOperations() { /* * When a standalone 0) then return]]>"; JSONObject jsonObject = XML.toJSONObject(xmlStr); - assertTrue("1. 3 items", 3 == jsonObject.length()); - assertTrue("1. empty tag1", "".equals(jsonObject.get("tag1"))); - assertTrue("1. empty tag2", "".equals(jsonObject.get("tag2"))); - assertTrue("1. content found", "if (a < b && a > 0) then return".equals(jsonObject.get("content"))); + assertEquals(3, jsonObject.length(), "1. 3 items"); + assertEquals("", jsonObject.get("tag1"), "1. empty tag1"); + assertEquals("", jsonObject.get("tag2"), "1. empty tag2"); + assertEquals("if (a < b && a > 0) then return", jsonObject.get("content"), "1. content found"); // multiple consecutive standalone cdatas are accumulated into an array xmlStr = " 0) then return]]>"; jsonObject = XML.toJSONObject(xmlStr); - assertTrue("2. 3 items", 3 == jsonObject.length()); - assertTrue("2. empty tag1", "".equals(jsonObject.get("tag1"))); - assertTrue("2. empty tag2", "".equals(jsonObject.get("tag2"))); - assertTrue("2. content array found", jsonObject.get("content") instanceof JSONArray); + assertEquals(3, jsonObject.length(), "2. 3 items"); + assertEquals("", jsonObject.get("tag1"), "2. empty tag1"); + assertEquals("", jsonObject.get("tag2"), "2. empty tag2"); + assertTrue(jsonObject.get("content") instanceof JSONArray, "2. content array found"); JSONArray jsonArray = jsonObject.getJSONArray("content"); - assertTrue("2. array size", jsonArray.length() == 2); - assertTrue("2. content array entry 0", "if (a < b && a > 0) then return".equals(jsonArray.get(0))); - assertTrue("2. content array entry 1", "here is another cdata".equals(jsonArray.get(1))); + assertEquals(2, jsonArray.length(), "2. array size"); + assertEquals("if (a < b && a > 0) then return", jsonArray.get(0), "2. content array entry 0"); + assertEquals("here is another cdata", jsonArray.get(1), "2. content array entry 1"); /* * text content is accumulated in a "content" inside a local JSONObject. @@ -619,8 +616,8 @@ public void contentOperations() { */ xmlStr = "value 1"; jsonObject = XML.toJSONObject(xmlStr); - assertTrue("3. 2 items", 1 == jsonObject.length()); - assertTrue("3. value tag1", "value 1".equals(jsonObject.get("tag1"))); + assertEquals(1, jsonObject.length(), "3. 2 items"); + assertEquals("value 1", jsonObject.get("tag1"), "3. value tag1"); /* * array-style text content (multiple tags with the same name) is @@ -629,13 +626,13 @@ public void contentOperations() { */ xmlStr = "value 12true"; jsonObject = XML.toJSONObject(xmlStr); - assertTrue("4. 1 item", 1 == jsonObject.length()); - assertTrue("4. content array found", jsonObject.get("tag1") instanceof JSONArray); + assertEquals(1, jsonObject.length(), "4. 1 item"); + assertTrue(jsonObject.get("tag1") instanceof JSONArray, "4. content array found"); jsonArray = jsonObject.getJSONArray("tag1"); - assertTrue("4. array size", jsonArray.length() == 3); - assertTrue("4. content array entry 0", "value 1".equals(jsonArray.get(0))); - assertTrue("4. content array entry 1", jsonArray.getInt(1) == 2); - assertTrue("4. content array entry 2", jsonArray.getBoolean(2) == true); + assertEquals(3, jsonArray.length(), "4. array size"); + assertEquals("value 1", jsonArray.get(0), "4. content array entry 0"); + assertEquals(2, jsonArray.getInt(1), "4. content array entry 1"); + assertTrue(jsonArray.getBoolean(2), "4. content array entry 2"); /* * Complex content is accumulated in a "content" field. For example, an element @@ -644,16 +641,16 @@ public void contentOperations() { */ xmlStr = "val1val2"; jsonObject = XML.toJSONObject(xmlStr); - assertTrue("5. 1 item", 1 == jsonObject.length()); - assertTrue("5. jsonObject found", jsonObject.get("tag1") instanceof JSONObject); + assertEquals(1, jsonObject.length(), "5. 1 item"); + assertTrue(jsonObject.get("tag1") instanceof JSONObject, "5. jsonObject found"); jsonObject = jsonObject.getJSONObject("tag1"); - assertTrue("5. 2 contained items", 2 == jsonObject.length()); - assertTrue("5. contained tag", "".equals(jsonObject.get("tag2"))); - assertTrue("5. contained content jsonArray found", jsonObject.get("content") instanceof JSONArray); + assertEquals(2, jsonObject.length(), "5. 2 contained items"); + assertEquals("", jsonObject.get("tag2"), "5. contained tag"); + assertTrue(jsonObject.get("content") instanceof JSONArray, "5. contained content jsonArray found"); jsonArray = jsonObject.getJSONArray("content"); - assertTrue("5. array size", jsonArray.length() == 2); - assertTrue("5. content array entry 0", "val1".equals(jsonArray.get(0))); - assertTrue("5. content array entry 1", "val2".equals(jsonArray.get(1))); + assertEquals(2, jsonArray.length(), "5. array size"); + assertEquals("val1", jsonArray.get(0), "5. content array entry 0"); + assertEquals("val2", jsonArray.get(1), "5. content array entry 1"); /* * If there is only 1 complex text content, then it is accumulated in a @@ -661,11 +658,11 @@ public void contentOperations() { */ xmlStr = "val1"; jsonObject = XML.toJSONObject(xmlStr); - assertTrue("6. 1 item", 1 == jsonObject.length()); - assertTrue("6. jsonObject found", jsonObject.get("tag1") instanceof JSONObject); + assertEquals(1, jsonObject.length(), "6. 1 item"); + assertTrue(jsonObject.get("tag1") instanceof JSONObject, "6. jsonObject found"); jsonObject = jsonObject.getJSONObject("tag1"); - assertTrue("6. contained content found", "val1".equals(jsonObject.get("content"))); - assertTrue("6. contained tag2", "".equals(jsonObject.get("tag2"))); + assertEquals("val1", jsonObject.get("content"), "6. contained content found"); + assertEquals("", jsonObject.get("tag2"), "6. contained tag2"); /* * In this corner case, the content sibling happens to have key=content @@ -674,15 +671,15 @@ public void contentOperations() { */ xmlStr = "val1"; jsonObject = XML.toJSONObject(xmlStr); - assertTrue("7. 1 item", 1 == jsonObject.length()); - assertTrue("7. jsonArray found", jsonObject.get("tag1") instanceof JSONArray); + assertEquals(1, jsonObject.length(), "7. 1 item"); + assertTrue(jsonObject.get("tag1") instanceof JSONArray, "7. jsonArray found"); jsonArray = jsonObject.getJSONArray("tag1"); - assertTrue("array size 1", jsonArray.length() == 1); - assertTrue("7. contained array found", jsonArray.get(0) instanceof JSONArray); + assertEquals(1, jsonArray.length(), "array size 1"); + assertTrue(jsonArray.get(0) instanceof JSONArray, "7. contained array found"); jsonArray = jsonArray.getJSONArray(0); - assertTrue("7. inner array size 2", jsonArray.length() == 2); - assertTrue("7. inner array item 0", "val1".equals(jsonArray.get(0))); - assertTrue("7. inner array item 1", "".equals(jsonArray.get(1))); + assertEquals(2, jsonArray.length(), "7. inner array size 2"); + assertEquals("val1", jsonArray.get(0), "7. inner array item 0"); + assertEquals("", jsonArray.get(1), "7. inner array item 1"); /* * Confirm behavior of original issue @@ -724,7 +721,7 @@ public void contentOperations() { * * */ - assertTrue("nothing to test here, see comment on created XML, above", true); + assertTrue(true, "nothing to test here, see comment on created XML, above"); } /** @@ -763,9 +760,9 @@ private void compareReaderToJSONObject(String xmlStr, String expectedStr) { * @throws IOException */ private void compareFileToJSONObject(String xmlStr, String expectedStr) { - try { + assertDoesNotThrow(() -> { JSONObject expectedJsonObject = new JSONObject(expectedStr); - File tempFile = this.testFolder.newFile("fileToJSONObject.xml"); + File tempFile = File.createTempFile("fileToJSONObject.xml", null, this.testFolder); FileWriter fileWriter = new FileWriter(tempFile); try { fileWriter.write(xmlStr); @@ -776,20 +773,18 @@ private void compareFileToJSONObject(String xmlStr, String expectedStr) { Reader reader = new FileReader(tempFile); try { JSONObject jsonObject = XML.toJSONObject(reader); - Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject); + Util.compareActualVsExpectedJsonObjects(jsonObject, expectedJsonObject); } finally { reader.close(); } - } catch (IOException e) { - fail("Error: " +e.getMessage()); - } + }, "Error: "); } /** * JSON string lost leading zero and converted "True" to true. */ @Test - public void testToJSONArray_jsonOutput() { + void toJSONArray_jsonOutput() { final String originalXml = "011000True"; final JSONObject expectedJson = new JSONObject("{\"root\":{\"item\":{\"id\":1},\"id\":[1,1,0,0],\"title\":true}}"); final JSONObject actualJsonOutput = XML.toJSONObject(originalXml, false); @@ -801,7 +796,7 @@ public void testToJSONArray_jsonOutput() { * JSON string cannot be reverted to original xml. */ @Test - public void testToJSONArray_reversibility() { + void toJSONArray_reversibility() { final String originalXml = "011000True"; final String revertedXml = XML.toString(XML.toJSONObject(originalXml, false)); @@ -812,7 +807,7 @@ public void testToJSONArray_reversibility() { * test passes when using the new method toJsonArray. */ @Test - public void testToJsonXML() { + void toJsonXML() { final String originalXml = "011000True"; final JSONObject expected = new JSONObject("{\"root\":{\"item\":{\"id\":\"01\"},\"id\":[\"01\",\"1\",\"00\",\"0\"],\"title\":\"True\"}}"); @@ -825,17 +820,17 @@ public void testToJsonXML() { // the order of the elements may be differnet as well. final String expectedReverseXml = "01011000True"; - assertEquals("length",expectedReverseXml.length(), reverseXml.length()); - assertTrue("array contents", reverseXml.contains("011000")); - assertTrue("item contents", reverseXml.contains("01")); - assertTrue("title contents", reverseXml.contains("True")); + assertEquals(expectedReverseXml.length(), reverseXml.length(), "length"); + assertTrue(reverseXml.contains("011000"), "array contents"); + assertTrue(reverseXml.contains("01"), "item contents"); + assertTrue(reverseXml.contains("True"), "title contents"); } - + /** * test to validate certain conditions of XML unescaping. */ @Test - public void testUnescape() { + void unescape() { assertEquals("{\"xml\":\"Can cope <;\"}", XML.toJSONObject("Can cope <; ").toString()); assertEquals("Can cope <; ", XML.unescape("Can cope <; ")); @@ -868,7 +863,7 @@ public void testUnescape() { * test passes when xsi:nil="true" converting to null (JSON specification-like nil conversion enabled) */ @Test - public void testToJsonWithNullWhenNilConversionEnabled() { + void toJsonWithNullWhenNilConversionEnabled() { final String originalXml = ""; final String expectedJsonString = "{\"root\":{\"id\":null}}"; @@ -884,7 +879,7 @@ public void testToJsonWithNullWhenNilConversionEnabled() { * test passes when xsi:nil="true" not converting to null (JSON specification-like nil conversion disabled) */ @Test - public void testToJsonWithNullWhenNilConversionDisabled() { + void toJsonWithNullWhenNilConversionDisabled() { final String originalXml = ""; final String expectedJsonString = "{\"root\":{\"id\":{\"xsi:nil\":true}}}"; @@ -896,7 +891,7 @@ public void testToJsonWithNullWhenNilConversionDisabled() { * Tests to verify that supported escapes in XML are converted to actual values. */ @Test - public void testIssue537CaseSensitiveHexEscapeMinimal(){ + void issue537CaseSensitiveHexEscapeMinimal(){ String xmlStr = "\n"+ "Neutrophils.Hypersegmented | Bld-Ser-Plas"; @@ -911,8 +906,8 @@ public void testIssue537CaseSensitiveHexEscapeMinimal(){ * Tests to verify that supported escapes in XML are converted to actual values. */ @Test - public void testIssue537CaseSensitiveHexEscapeFullFile(){ - try { + void issue537CaseSensitiveHexEscapeFullFile(){ + assertDoesNotThrow(() -> { InputStream xmlStream = null; try { xmlStream = XMLTest.class.getClassLoader().getResourceAsStream("Issue537.xml"); @@ -922,7 +917,7 @@ public void testIssue537CaseSensitiveHexEscapeFullFile(){ try { jsonStream = XMLTest.class.getClassLoader().getResourceAsStream("Issue537.json"); final JSONObject expected = new JSONObject(new JSONTokener(jsonStream)); - Util.compareActualVsExpectedJsonObjects(actual,expected); + Util.compareActualVsExpectedJsonObjects(actual, expected); } finally { if (jsonStream != null) { jsonStream.close(); @@ -933,30 +928,28 @@ public void testIssue537CaseSensitiveHexEscapeFullFile(){ xmlStream.close(); } } - } catch (IOException e) { - fail("file writer error: " +e.getMessage()); - } + }, "file writer error: "); } /** * Tests to verify that supported escapes in XML are converted to actual values. */ @Test - public void testIssue537CaseSensitiveHexUnEscapeDirect(){ + void issue537CaseSensitiveHexUnEscapeDirect(){ String origStr = "Neutrophils.Hypersegmented | Bld-Ser-Plas"; String expectedStr = "Neutrophils.Hypersegmented | Bld-Ser-Plas"; String actualStr = XML.unescape(origStr); - assertEquals("Case insensitive Entity unescape", expectedStr, actualStr); + assertEquals(expectedStr, actualStr, "Case insensitive Entity unescape"); } /** * test passes when xsi:type="java.lang.String" not converting to string */ @Test - public void testToJsonWithTypeWhenTypeConversionDisabled() { + void toJsonWithTypeWhenTypeConversionDisabled() { String originalXml = "1234"; String expectedJsonString = "{\"root\":{\"id\":{\"xsi:type\":\"string\",\"content\":1234}}}"; JSONObject expectedJson = new JSONObject(expectedJsonString); @@ -968,7 +961,7 @@ public void testToJsonWithTypeWhenTypeConversionDisabled() { * test passes when xsi:type="java.lang.String" converting to String */ @Test - public void testToJsonWithTypeWhenTypeConversionEnabled() { + void toJsonWithTypeWhenTypeConversionEnabled() { String originalXml = "1234" + "1234"; String expectedJsonString = "{\"root\":{\"id2\":1234,\"id1\":\"1234\"}}"; @@ -989,7 +982,7 @@ public void testToJsonWithTypeWhenTypeConversionEnabled() { } @Test - public void testToJsonWithXSITypeWhenTypeConversionEnabled() { + void toJsonWithXSITypeWhenTypeConversionEnabled() { String originalXml = "1234554321"; String expectedJsonString = "{\"root\":{\"asString\":\"12345\",\"asInt\":54321}}"; @@ -1010,7 +1003,7 @@ public void testToJsonWithXSITypeWhenTypeConversionEnabled() { } @Test - public void testToJsonWithXSITypeWhenTypeConversionNotEnabledOnOne() { + void toJsonWithXSITypeWhenTypeConversionNotEnabledOnOne() { String originalXml = "1234554321"; String expectedJsonString = "{\"root\":{\"asString\":\"12345\",\"asInt\":54321}}"; JSONObject expectedJson = new JSONObject(expectedJsonString); @@ -1025,7 +1018,7 @@ public void testToJsonWithXSITypeWhenTypeConversionNotEnabledOnOne() { } @Test - public void testXSITypeMapNotModifiable() { + void xSITypeMapNotModifiable() { Map> xsiTypeMap = new HashMap>(); XMLParserConfiguration config = new XMLParserConfiguration().withXsiTypeMap(xsiTypeMap); xsiTypeMap.put("string", new XMLXsiTypeConverter() { @@ -1033,7 +1026,7 @@ public void testXSITypeMapNotModifiable() { return value; } }); - assertEquals("Config Conversion Map size is expected to be 0", 0, config.getXsiTypeMap().size()); + assertEquals(0, config.getXsiTypeMap().size(), "Config Conversion Map size is expected to be 0"); try { config.getXsiTypeMap().put("boolean", new XMLXsiTypeConverter() { @@ -1046,7 +1039,7 @@ public void testXSITypeMapNotModifiable() { } @Test - public void testIndentComplicatedJsonObject(){ + void indentComplicatedJsonObject(){ String str = "{\n" + " \"success\": true,\n" + " \"error\": null,\n" + @@ -1179,7 +1172,7 @@ public void testIndentComplicatedJsonObject(){ } @Test - public void shouldCreateExplicitEndTagWithEmptyValueWhenConfigured(){ + void shouldCreateExplicitEndTagWithEmptyValueWhenConfigured(){ String jsonString = "{outer:{innerOne:\"\", innerTwo:\"two\"}}"; JSONObject jsonObject = new JSONObject(jsonString); String expectedXmlString = "two"; @@ -1190,7 +1183,7 @@ public void shouldCreateExplicitEndTagWithEmptyValueWhenConfigured(){ } @Test - public void shouldNotCreateExplicitEndTagWithEmptyValueWhenNotConfigured(){ + void shouldNotCreateExplicitEndTagWithEmptyValueWhenNotConfigured(){ String jsonString = "{outer:{innerOne:\"\", innerTwo:\"two\"}}"; JSONObject jsonObject = new JSONObject(jsonString); String expectedXmlString = "two"; @@ -1202,7 +1195,7 @@ public void shouldNotCreateExplicitEndTagWithEmptyValueWhenNotConfigured(){ @Test - public void testIndentSimpleJsonObject(){ + void indentSimpleJsonObject(){ String str = "{ \"employee\": { \n" + " \"name\": \"sonoo\", \n" + " \"salary\": 56000, \n" + @@ -1223,7 +1216,7 @@ public void testIndentSimpleJsonObject(){ } @Test - public void testIndentSimpleJsonArray(){ + void indentSimpleJsonArray(){ String str = "[ \n" + " {\"name\":\"Ram\", \"email\":\"Ram@gmail.com\"}, \n" + " {\"name\":\"Bob\", \"email\":\"bob32@gmail.com\"} \n" + @@ -1246,7 +1239,7 @@ public void testIndentSimpleJsonArray(){ } @Test - public void testIndentComplicatedJsonObjectWithArrayAndWithConfig(){ + void indentComplicatedJsonObjectWithArrayAndWithConfig(){ try (InputStream jsonStream = XMLTest.class.getClassLoader().getResourceAsStream("Issue593.json")) { final JSONObject object = new JSONObject(new JSONTokener(jsonStream)); String actualString = XML.toString(object, null, XMLParserConfiguration.KEEP_STRINGS, 2); @@ -1266,7 +1259,7 @@ public void testIndentComplicatedJsonObjectWithArrayAndWithConfig(){ } @Test - public void testMaxNestingDepthOf42IsRespected() { + void maxNestingDepthOf42IsRespected() { final String wayTooLongMalformedXML = new String(new char[6000]).replace("\0", ""); final int maxNestingDepth = 42; @@ -1276,13 +1269,13 @@ public void testMaxNestingDepthOf42IsRespected() { fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Wrong throwable thrown: not expecting message <" + e.getMessage() + ">", - e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth)); + assertTrue(e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth), + "Wrong throwable thrown: not expecting message <" + e.getMessage() + ">"); } } @Test - public void testMaxNestingDepthIsRespectedWithValidXML() { + void maxNestingDepthIsRespectedWithValidXML() { final String perfectlyFineXML = "\n" + " \n" + " sonoo\n" + @@ -1298,13 +1291,13 @@ public void testMaxNestingDepthIsRespectedWithValidXML() { fail("Expecting a JSONException"); } catch (JSONException e) { - assertTrue("Wrong throwable thrown: not expecting message <" + e.getMessage() + ">", - e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth)); + assertTrue(e.getMessage().startsWith("Maximum nesting depth of " + maxNestingDepth), + "Wrong throwable thrown: not expecting message <" + e.getMessage() + ">"); } } @Test - public void testMaxNestingDepthWithValidFittingXML() { + void maxNestingDepthWithValidFittingXML() { final String perfectlyFineXML = "\n" + " \n" + " sonoo\n" +