Skip to content

Commit 8ebe69f

Browse files
psysanepsysane
authored andcommitted
Example unit test for the article "Count with JsonPath"
1 parent ce4b429 commit 8ebe69f

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"items": {
3+
"book": [
4+
{
5+
"author": "Arthur Conan Doyle",
6+
"title": "Sherlock Holmes",
7+
"price": 8.99
8+
},
9+
{
10+
"author": "J. R. R. Tolkien",
11+
"title": "The Lord of the Rings",
12+
"isbn": "0-395-19395-8",
13+
"price": 22.99
14+
}
15+
],
16+
"bicycle": {
17+
"color": "red",
18+
"price": 19.95
19+
}
20+
}
21+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.baeldung.jsonpath.introduction;
2+
3+
import static org.junit.Assert.assertEquals;
4+
5+
import java.io.File;
6+
import java.io.IOException;
7+
import java.nio.charset.Charset;
8+
import java.nio.charset.StandardCharsets;
9+
import java.nio.file.Files;
10+
import java.util.Map;
11+
12+
import org.junit.BeforeClass;
13+
import org.junit.Test;
14+
15+
import com.jayway.jsonpath.JsonPath;
16+
17+
import net.minidev.json.JSONArray;
18+
19+
public class JsonPathUnitTest {
20+
21+
private static String json;
22+
private static File jsonFile = new File("src/main/resources/online_store.json");
23+
24+
private static String readFile(File file, Charset charset) throws IOException {
25+
return new String(Files.readAllBytes(file.toPath()), charset);
26+
}
27+
28+
@BeforeClass
29+
public static void init() throws IOException {
30+
json = readFile(jsonFile, StandardCharsets.UTF_8);
31+
}
32+
33+
@Test
34+
public void shouldMatchCountOfObjects() {
35+
Map<String, String> objectMap = JsonPath.read(json, "$");
36+
assertEquals(1, objectMap.keySet()
37+
.size());
38+
}
39+
40+
@Test
41+
public void shouldMatchCountOfArrays() {
42+
JSONArray jsonArray = JsonPath.read(json, "$.items.book[*]");
43+
assertEquals(2, jsonArray.size());
44+
}
45+
46+
}

0 commit comments

Comments
 (0)