View Javadoc
1   package dev.aherscu.qa.testing.utils.assertions;
2   
3   import org.hamcrest.Description;
4   import org.hamcrest.Matcher;
5   import org.hamcrest.TypeSafeMatcher;
6   
7   import com.jayway.jsonpath.JsonPath;
8   import com.jayway.jsonpath.JsonPathException;
9   import com.jayway.jsonpath.PathNotFoundException;
10  import com.jayway.jsonpath.ReadContext;
11  
12  public class WithJsonPath<T> extends TypeSafeMatcher<ReadContext> {
13      private final JsonPath   jsonPath;
14      private final Matcher<T> resultMatcher;
15  
16      public WithJsonPath(JsonPath jsonPath, Matcher<T> resultMatcher) {
17          this.jsonPath = jsonPath;
18          this.resultMatcher = resultMatcher;
19      }
20  
21      @Override
22      protected boolean matchesSafely(ReadContext context) {
23          try {
24              T value = context.read(jsonPath);
25              return resultMatcher.matches(value);
26          } catch (JsonPathException e) {
27              return false;
28          }
29      }
30  
31      public void describeTo(Description description) {
32          description
33              .appendText("with json path ")
34              .appendValue(jsonPath.getPath())
35              .appendText(" evaluated to ")
36              .appendDescriptionOf(resultMatcher);
37      }
38  
39      @Override
40      protected void describeMismatchSafely(ReadContext context,
41          Description mismatchDescription) {
42          try {
43              T value = jsonPath.read(context.jsonString());
44              mismatchDescription
45                  .appendText("json path ")
46                  .appendValue(jsonPath.getPath())
47                  .appendText(" was evaluated to ")
48                  .appendValue(value);
49          } catch (PathNotFoundException e) {
50              mismatchDescription
51                  .appendText("json path ")
52                  .appendValue(jsonPath.getPath())
53                  .appendText(" was not found in ")
54                  .appendValue(context.json());
55          } catch (JsonPathException e) {
56              mismatchDescription
57                  .appendText("was ")
58                  .appendValue(context.json());
59          }
60      }
61  
62  }