1
2
3
4
5 package com.jcabi.github;
6
7 import jakarta.json.Json;
8 import jakarta.json.JsonArray;
9 import jakarta.json.JsonObject;
10 import java.io.IOException;
11 import java.nio.charset.StandardCharsets;
12 import org.apache.commons.io.IOUtils;
13 import org.hamcrest.MatcherAssert;
14 import org.hamcrest.Matchers;
15 import org.junit.jupiter.api.Test;
16
17
18
19
20
21
22 @SuppressWarnings("PMD.AvoidDuplicateLiterals")
23 final class SmartJsonTest {
24
25 @Test
26 void fetchesStringFromJson() throws IOException {
27 MatcherAssert.assertThat(
28 "Values are not equal",
29 new SmartJson(
30 SmartJsonTest.json("{\"first\": \"a\"}")
31 ).text("first"),
32 Matchers.equalTo("a")
33 );
34 }
35
36 @Test
37 void fetchesNumberFromJson() throws IOException {
38 MatcherAssert.assertThat(
39 "Values are not equal",
40 new SmartJson(
41 SmartJsonTest.json("{\"second\": 1}")
42 ).number("second"),
43 Matchers.equalTo(1)
44 );
45 }
46
47 @Test
48 void fetchesArrayFromJson() throws IOException {
49 MatcherAssert.assertThat(
50 "Collection size is incorrect",
51 new SmartJson(
52 SmartJsonTest.json("{\"arr\": [1, 2]}")
53 ).value("arr", JsonArray.class),
54 Matchers.hasSize(2)
55 );
56 }
57
58 @Test
59 void fetchesObjectFromJson() throws IOException {
60 MatcherAssert.assertThat(
61 "Collection size is incorrect",
62 new SmartJson(
63 SmartJsonTest.json("{\"o\": {\"foo\": [1]}}")
64 ).value("o", JsonObject.class).getJsonArray("foo"),
65 Matchers.hasSize(1)
66 );
67 }
68
69 @Test
70 void checksNotNullKeyNotPresent() throws IOException {
71 MatcherAssert.assertThat(
72 "Values are not equal",
73 new SmartJson(
74 SmartJsonTest.json("{\"first\": \"a\"}")
75 ).hasNotNull("second"),
76 Matchers.equalTo(false)
77 );
78 }
79
80 @Test
81 void checksNotNullKeyPresentAndNull() throws IOException {
82 MatcherAssert.assertThat(
83 "Values are not equal",
84 new SmartJson(
85 SmartJsonTest.json("{\"first\": null}")
86 ).hasNotNull("first"),
87 Matchers.equalTo(false)
88 );
89 }
90
91 @Test
92 void checksNotNullKeyPresentAndNotNull() throws IOException {
93 MatcherAssert.assertThat(
94 "Values are not equal",
95 new SmartJson(
96 SmartJsonTest.json("{\"first\": \"a\"}")
97 ).hasNotNull("first"),
98 Matchers.equalTo(true)
99 );
100 }
101
102
103
104
105
106
107 private static JsonReadable json(final String txt) {
108 return () -> Json.createReader(
109 IOUtils.toInputStream(txt, StandardCharsets.UTF_8)
110 ).readObject();
111 }
112
113 }