0
# Fluent Assertion Interface
1
2
Object-oriented fluent API for creating readable assertion chains with detailed error reporting and method chaining support. This interface provides an alternative to the matcher-based approach, offering a more traditional assertion style for complex JSON validation scenarios.
3
4
## Capabilities
5
6
### JsonAsserter Factory Methods
7
8
Static factory methods for creating JsonAsserter instances from various JSON input sources.
9
10
```java { .api }
11
/**
12
* Creates a JsonAsserter from a JSON string
13
* @param json JSON document as string
14
* @return JsonAsserter instance for fluent assertions
15
* @throws ParseException when the JSON cannot be parsed
16
*/
17
public static JsonAsserter with(String json);
18
19
/**
20
* Creates a JsonAsserter from a Reader
21
* @param reader Reader containing JSON document
22
* @return JsonAsserter instance for fluent assertions
23
* @throws IOException when reading fails
24
* @throws ParseException when the JSON cannot be parsed
25
*/
26
public static JsonAsserter with(Reader reader) throws IOException;
27
28
/**
29
* Creates a JsonAsserter from an InputStream
30
* @param is InputStream containing JSON document
31
* @return JsonAsserter instance for fluent assertions
32
* @throws IOException when reading fails
33
* @throws ParseException when the JSON cannot be parsed
34
*/
35
public static JsonAsserter with(InputStream is) throws IOException;
36
```
37
38
**Usage Examples:**
39
40
```java
41
import static com.jayway.jsonassert.JsonAssert.with;
42
import java.io.*;
43
44
// From string
45
String jsonString = "{\"user\":{\"name\":\"Alice\",\"age\":30}}";
46
JsonAsserter asserter = with(jsonString);
47
48
// From file
49
FileReader reader = new FileReader("user.json");
50
JsonAsserter fileAsserter = with(reader);
51
52
// From input stream
53
InputStream stream = getClass().getResourceAsStream("/data.json");
54
JsonAsserter streamAsserter = with(stream);
55
```
56
57
### Core Assertion Methods
58
59
Primary assertion methods for validating JSON path values using Hamcrest matchers or direct value comparison.
60
61
```java { .api }
62
/**
63
* Asserts that the value at the specified path matches the given Hamcrest matcher
64
* @param path JsonPath expression as string
65
* @param matcher Hamcrest matcher to validate the path value
66
* @return this JsonAsserter for method chaining
67
* @throws AssertionError if path doesn't exist or value doesn't match
68
*/
69
<T> JsonAsserter assertThat(String path, Matcher<T> matcher);
70
71
/**
72
* Asserts that the value at the specified path matches the given matcher with custom error message
73
* @param path JsonPath expression as string
74
* @param matcher Hamcrest matcher to validate the path value
75
* @param message Custom error message for assertion failures
76
* @return this JsonAsserter for method chaining
77
* @throws AssertionError if path doesn't exist or value doesn't match
78
*/
79
<T> JsonAsserter assertThat(String path, Matcher<T> matcher, String message);
80
81
/**
82
* Asserts that the value at the specified path equals the expected value
83
* @param path JsonPath expression as string
84
* @param expected Expected value for comparison
85
* @return this JsonAsserter for method chaining
86
* @throws AssertionError if path doesn't exist or values are not equal
87
*/
88
<T> JsonAsserter assertEquals(String path, T expected);
89
90
/**
91
* Asserts that the value at the specified path equals the expected value with custom error message
92
* @param path JsonPath expression as string
93
* @param expected Expected value for comparison
94
* @param message Custom error message for assertion failures
95
* @return this JsonAsserter for method chaining
96
* @throws AssertionError if path doesn't exist or values are not equal
97
*/
98
<T> JsonAsserter assertEquals(String path, T expected, String message);
99
```
100
101
**Usage Examples:**
102
103
```java
104
import static com.jayway.jsonassert.JsonAssert.with;
105
import static org.hamcrest.Matchers.*;
106
107
String json = "{\"user\":{\"name\":\"Alice\",\"age\":30,\"roles\":[\"admin\",\"user\"]}}";
108
109
// Using Hamcrest matchers
110
with(json)
111
.assertThat("$.user.name", equalTo("Alice"))
112
.assertThat("$.user.age", greaterThan(18))
113
.assertThat("$.user.roles", hasSize(2))
114
.assertThat("$.user.roles", hasItem("admin"));
115
116
// Direct value comparison
117
with(json)
118
.assertEquals("$.user.name", "Alice")
119
.assertEquals("$.user.age", 30);
120
121
// Custom error messages
122
with(json)
123
.assertThat("$.user.age", greaterThan(21), "User must be over 21")
124
.assertEquals("$.user.name", "Alice", "User name should be Alice");
125
```
126
127
### Path Existence Assertions
128
129
Methods for asserting whether paths exist or are undefined within the JSON document.
130
131
```java { .api }
132
/**
133
* Asserts that the specified path does not exist in the JSON document
134
* @param path JsonPath expression as string
135
* @return this JsonAsserter for method chaining
136
* @throws AssertionError if the path exists
137
*/
138
JsonAsserter assertNotDefined(String path);
139
140
/**
141
* Asserts that the specified path does not exist with custom error message
142
* @param path JsonPath expression as string
143
* @param message Custom error message for assertion failures
144
* @return this JsonAsserter for method chaining
145
* @throws AssertionError if the path exists
146
*/
147
JsonAsserter assertNotDefined(String path, String message);
148
```
149
150
**Usage Examples:**
151
152
```java
153
String json = "{\"user\":{\"name\":\"Alice\",\"age\":30}}";
154
155
with(json)
156
.assertNotDefined("$.user.email")
157
.assertNotDefined("$.admin", "Document should not contain admin section")
158
.assertNotDefined("$.user.password");
159
```
160
161
### Null Value Assertions
162
163
Specialized methods for asserting null and non-null values at specified paths.
164
165
```java { .api }
166
/**
167
* Asserts that the value at the specified path is null
168
* @param path JsonPath expression as string
169
* @return this JsonAsserter for method chaining
170
* @throws AssertionError if path doesn't exist or value is not null
171
*/
172
JsonAsserter assertNull(String path);
173
174
/**
175
* Asserts that the value at the specified path is null with custom error message
176
* @param path JsonPath expression as string
177
* @param message Custom error message for assertion failures
178
* @return this JsonAsserter for method chaining
179
* @throws AssertionError if path doesn't exist or value is not null
180
*/
181
JsonAsserter assertNull(String path, String message);
182
183
/**
184
* Asserts that the value at the specified path is NOT null
185
* @param path JsonPath expression as string
186
* @return this JsonAsserter for method chaining
187
* @throws AssertionError if path doesn't exist or value is null
188
*/
189
<T> JsonAsserter assertNotNull(String path);
190
191
/**
192
* Asserts that the value at the specified path is NOT null with custom error message
193
* @param path JsonPath expression as string
194
* @param message Custom error message for assertion failures
195
* @return this JsonAsserter for method chaining
196
* @throws AssertionError if path doesn't exist or value is null
197
*/
198
<T> JsonAsserter assertNotNull(String path, String message);
199
```
200
201
**Usage Examples:**
202
203
```java
204
String json = "{\"user\":{\"name\":\"Alice\",\"email\":null,\"age\":30}}";
205
206
with(json)
207
.assertNull("$.user.email")
208
.assertNull("$.user.email", "Email should not be set")
209
.assertNotNull("$.user.name")
210
.assertNotNull("$.user.age", "Age is required");
211
```
212
213
### Method Chaining Support
214
215
Syntactic sugar method for creating readable assertion chains.
216
217
```java { .api }
218
/**
219
* Syntactic sugar to allow chaining assertions with a separating and() statement
220
* @return this JsonAsserter for continued method chaining
221
*/
222
JsonAsserter and();
223
```
224
225
**Usage Examples:**
226
227
```java
228
String json = "{\"user\":{\"firstName\":\"Alice\",\"lastName\":\"Smith\",\"age\":30,\"active\":true}}";
229
230
// Readable assertion chains
231
with(json)
232
.assertThat("$.user.firstName", equalTo("Alice"))
233
.and()
234
.assertThat("$.user.lastName", equalTo("Smith"))
235
.and()
236
.assertThat("$.user.age", greaterThan(18))
237
.and()
238
.assertEquals("$.user.active", true);
239
240
// Complex validation chain
241
with(json)
242
.assertNotNull("$.user.firstName", "First name is required")
243
.and()
244
.assertNotNull("$.user.lastName", "Last name is required")
245
.and()
246
.assertThat("$.user.age", allOf(greaterThan(0), lessThan(150)))
247
.and()
248
.assertNotDefined("$.user.password")
249
.and()
250
.assertNull("$.user.deletedAt");
251
```
252
253
## Error Handling and Reporting
254
255
The fluent assertion interface provides detailed error messages that include:
256
257
- **Path Context**: The JsonPath expression that failed
258
- **Expected vs Actual**: Clear comparison of expected and actual values
259
- **Custom Messages**: User-provided error descriptions
260
- **Exception Chain**: Original parsing or path evaluation errors
261
262
**Example Error Messages:**
263
264
```java
265
// Path not found error
266
"Error reading JSON path [$.user.missing]"
267
268
// Value mismatch error
269
"JSON path [$.user.age] doesn't match.\nExpected: <25>\nActual: <30>"
270
271
// Custom message error
272
"JSON Assert Error: User must be over 21\nExpected: <greater than 21>\nActual: <18>"
273
```
274
275
## Integration with JsonPath Configuration
276
277
The fluent assertion interface respects the current JsonPath configuration for parsing and path evaluation:
278
279
```java
280
import com.jayway.jsonpath.Configuration;
281
import com.jayway.jsonpath.Option;
282
283
// Configure strict parsing
284
Configuration.setDefaults(Configuration.defaultConfiguration()
285
.addOptions(Option.SUPPRESS_EXCEPTIONS));
286
287
// Assertions will use the configured behavior
288
with(json)
289
.assertThat("$.path", equalTo(expectedValue));
290
```
291
292
## Performance Considerations
293
294
- **Document Parsing**: JSON is parsed once when creating the JsonAsserter instance
295
- **Path Evaluation**: Each assertion method evaluates its path independently
296
- **Error Handling**: Detailed error reporting may impact performance in high-volume scenarios
297
- **Memory Usage**: The parsed JSON document is held in memory for the lifetime of the JsonAsserter