|
| 1 | +package com.baeldung.jsonexception; |
| 2 | + |
| 3 | +import org.json.JSONArray; |
| 4 | +import org.json.JSONException; |
| 5 | +import org.json.JSONObject; |
| 6 | +import org.junit.jupiter.api.Test; |
| 7 | + |
| 8 | +import static org.junit.jupiter.api.Assertions.*; |
| 9 | + |
| 10 | +class JsonParsingUnitTest { |
| 11 | + |
| 12 | + @Test |
| 13 | + void givenArrayString_whenParsedAsObject_thenThrowException() { |
| 14 | + String jsonArray = "[{\"id\":1, \"name\":\"Alice\"}]"; |
| 15 | + assertThrows(JSONException.class, () -> new JSONObject(jsonArray)); |
| 16 | + } |
| 17 | + |
| 18 | + @Test |
| 19 | + void givenArrayString_whenParsedAsArray_thenSuccess() { |
| 20 | + String jsonArray = "[{\"id\":1, \"name\":\"Alice\"}]"; |
| 21 | + JSONArray array = new JSONArray(jsonArray); |
| 22 | + assertEquals("Alice", array.getJSONObject(0).getString("name")); |
| 23 | + } |
| 24 | + |
| 25 | + @Test |
| 26 | + void givenInvalidJson_whenParsed_thenThrowException() { |
| 27 | + String invalid = "<html>Server Error</html>"; |
| 28 | + assertThrows(JSONException.class, () -> new JSONObject(invalid)); |
| 29 | + } |
| 30 | + |
| 31 | + @Test |
| 32 | + void givenEmptyString_whenParsed_thenThrowException() { |
| 33 | + String empty = ""; |
| 34 | + assertThrows(JSONException.class, () -> new JSONObject(empty)); |
| 35 | + } |
| 36 | + |
| 37 | + @Test |
| 38 | + void givenValidJson_whenParsed_thenReturnExpectedValue() { |
| 39 | + String json = "{\"id\":101, \"status\":\"success\"}"; |
| 40 | + JSONObject obj = new JSONObject(json); |
| 41 | + assertEquals(101, obj.getInt("id")); |
| 42 | + assertEquals("success", obj.getString("status")); |
| 43 | + } |
| 44 | + |
| 45 | + @Test |
| 46 | + void givenUnknownJsonType_whenValidated_thenHandledGracefully() { |
| 47 | + String response = "[{\"id\":1}]"; |
| 48 | + Object parsed; |
| 49 | + if (response.trim().startsWith("{")) { |
| 50 | + parsed = new JSONObject(response); |
| 51 | + } else if (response.trim().startsWith("[")) { |
| 52 | + parsed = new JSONArray(response); |
| 53 | + } else { |
| 54 | + throw new JSONException("Invalid JSON"); |
| 55 | + } |
| 56 | + assertInstanceOf(JSONArray.class, parsed); |
| 57 | + } |
| 58 | +} |
| 59 | + |
0 commit comments