|
1 | 1 | package org.json.junit; |
2 | 2 |
|
3 | | -import static org.junit.Assert.assertEquals; |
4 | | -import static org.junit.Assert.assertSame; |
5 | | -import static org.junit.Assert.fail; |
| 3 | +import static org.junit.Assert.*; |
6 | 4 |
|
7 | 5 | import org.json.*; |
8 | 6 | import org.junit.Test; |
@@ -153,4 +151,62 @@ public void tokenListIsCopiedInConstructor() { |
153 | 151 | } |
154 | 152 | } |
155 | 153 |
|
| 154 | + /** |
| 155 | + * Coverage for JSONObject queryFrom() |
| 156 | + */ |
| 157 | + @Test |
| 158 | + public void queryFromJSONObject() { |
| 159 | + String str = "{"+ |
| 160 | + "\"stringKey\":\"hello world!\","+ |
| 161 | + "\"arrayKey\":[0,1,2],"+ |
| 162 | + "\"objectKey\": {"+ |
| 163 | + "\"a\":\"aVal\","+ |
| 164 | + "\"b\":\"bVal\""+ |
| 165 | + "}"+ |
| 166 | + "}"; |
| 167 | + JSONObject jsonObject = new JSONObject(str); |
| 168 | + Object obj = jsonObject.query("/stringKey"); |
| 169 | + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); |
| 170 | + obj = jsonObject.query("/arrayKey/1"); |
| 171 | + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); |
| 172 | + obj = jsonObject.query("/objectKey/b"); |
| 173 | + assertTrue("Expected bVal", "bVal".equals(obj)); |
| 174 | + try { |
| 175 | + obj = jsonObject.query("/a/b/c"); |
| 176 | + assertTrue("Expected JSONPointerException", false); |
| 177 | + } catch (JSONPointerException e) { |
| 178 | + assertTrue("Expected bad key/value exception", |
| 179 | + "value [null] is not an array or object therefore its key b cannot be resolved". |
| 180 | + equals(e.getMessage())); |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + /** |
| 185 | + * Coverage for JSONArray queryFrom() |
| 186 | + */ |
| 187 | + @Test |
| 188 | + public void queryFromJSONArray() { |
| 189 | + String str = "["+ |
| 190 | + "\"hello world!\","+ |
| 191 | + "[0,1,2],"+ |
| 192 | + "{"+ |
| 193 | + "\"a\":\"aVal\","+ |
| 194 | + "\"b\":\"bVal\""+ |
| 195 | + "}"+ |
| 196 | + "]"; |
| 197 | + JSONArray jsonArray = new JSONArray(str); |
| 198 | + Object obj = jsonArray.query("/0"); |
| 199 | + assertTrue("Expected 'hello world!'", "hello world!".equals(obj)); |
| 200 | + obj = jsonArray.query("/1/1"); |
| 201 | + assertTrue("Expected 1", Integer.valueOf(1).equals(obj)); |
| 202 | + obj = jsonArray.query("/2/b"); |
| 203 | + assertTrue("Expected bVal", "bVal".equals(obj)); |
| 204 | + try { |
| 205 | + obj = jsonArray.query("/a/b/c"); |
| 206 | + assertTrue("Expected JSONPointerException", false); |
| 207 | + } catch (JSONPointerException e) { |
| 208 | + assertTrue("Expected bad index exception", |
| 209 | + "a is not an array index".equals(e.getMessage())); |
| 210 | + } |
| 211 | + } |
156 | 212 | } |
0 commit comments