Best JSONassert code snippet using org.skyscreamer.jsonassert.ArrayValueMatcher.ArrayValueMatcher
Source:ArrayValueMatcherTest.java
...24import org.skyscreamer.jsonassert.comparator.CustomComparator;25import org.skyscreamer.jsonassert.comparator.DefaultComparator;26import org.skyscreamer.jsonassert.comparator.JSONComparator;27/**28 * Unit tests for ArrayValueMatcher29 * 30 * @author Duncan Mackinder31 *32 */33public class ArrayValueMatcherTest {34 private static final String ARRAY_OF_JSONOBJECTS = "{a:[{background:white,id:1,type:row},{background:grey,id:2,type:row},{background:white,id:3,type:row},{background:grey,id:4,type:row}]}";35 private static final String ARRAY_OF_INTEGERS = "{a:[1,2,3,4,5]}";36 private static final String ARRAY_OF_JSONARRAYS = "{a:[[6,7,8],[9,10,11],[12,13,14],[19,20,21,22]]}";37 private static final JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);38 private void doTest(String jsonPath, ArrayValueMatcher<Object> arrayValueMatcher, String expectedJSON,39 String actualJSON) throws JSONException {40 Customization customization = new Customization(jsonPath, arrayValueMatcher);41 JSONAssert.assertEquals(expectedJSON, actualJSON, new CustomComparator(JSONCompareMode.LENIENT, customization));42 }43 private void doFailingMatchTest(String jsonPath, ArrayValueMatcher<Object> arrayValueMatcher, String expectedJSON, String actualJSON, String expectedMessagePattern) throws JSONException {44 try {45 doTest(jsonPath, arrayValueMatcher, expectedJSON, actualJSON);46 }47 catch (AssertionError e) {48 String failureMessage = MessageFormat.format("Exception message ''{0}'', does not match expected pattern ''{1}''", e.getMessage(), expectedMessagePattern);49 assertTrue(failureMessage, e.getMessage().matches(expectedMessagePattern));50 return;51 }52 fail("AssertionError not thrown");53 }54 @Test55 public void matchesSecondElementOfJSONObjectArray() throws JSONException {56 doTest("a", new ArrayValueMatcher<Object>(comparator, 1), "{a:[{background:grey,id:2,type:row}]}", ARRAY_OF_JSONOBJECTS);57 }58 @Test59 public void failsWhenSecondElementOfJSONObjectArrayDoesNotMatch() throws JSONException {60 doFailingMatchTest("a",61 new ArrayValueMatcher<Object>(comparator, 1),62 "{a:[{background:DOES_NOT_MATCH,id:2,type:row}]}",63 ARRAY_OF_JSONOBJECTS,64 "a\\[1\\]\\.background\\s*Expected:\\s*DOES_NOT_MATCH\\s*got:\\s*grey\\s*");65 }66 @Test67 public void failsWhenThirdElementOfJSONObjectArrayDoesNotMatchInMultiplePlaces() throws JSONException {68 doFailingMatchTest("a",69 new ArrayValueMatcher<Object>(comparator, 2),70 "{a:[{background:DOES_NOT_MATCH,id:3,type:WRONG_TYPE}]}",71 ARRAY_OF_JSONOBJECTS,72 "a\\[2\\]\\.background\\s*Expected:\\s*DOES_NOT_MATCH\\s*got:\\s*white\\s*;\\s*a\\[2\\]\\.type\\s*Expected:\\s*WRONG_TYPE\\s*got:\\s*row\\s*");73 }74 @Test75 public void failsWhenTwoElementsOfJSONObjectArrayDoNotMatch() throws JSONException {76 doFailingMatchTest("a",77 new ArrayValueMatcher<Object>(comparator, 1, 2),78 "{a:[{background:DOES_NOT_MATCH,id:2,type:row},{background:white,id:3,type:WRONG_TYPE}]}",79 ARRAY_OF_JSONOBJECTS,80 "a\\[1\\]\\.background\\s*Expected:\\s*DOES_NOT_MATCH\\s*got:\\s*grey\\s*;\\s*a\\[2\\]\\.type\\s*Expected:\\s*WRONG_TYPE\\s*got:\\s*row\\s*");81 }82 @Test83 public void matchesThirdElementOfSimpleValueArray() throws JSONException {84 doTest("a", new ArrayValueMatcher<Object>(comparator, 2), "{a:[3]}", ARRAY_OF_INTEGERS);85 }86 @Test87 public void failsWhenTwoElementOfSimpleValueArrayDoNotMatch() throws JSONException {88 doFailingMatchTest("a", new ArrayValueMatcher<Object>(comparator, 3, 4), "{a:[3,4]}", ARRAY_OF_INTEGERS,89 "a\\[3\\]\\s*Expected:\\s3\\s*got:\\s*4\\s*;\\s*a\\[4\\]\\s*Expected:\\s*4\\s*got:\\s*5\\s*");90 }91 @Test92 public void matchesFirstElementOfArrayOfJSONArrays() throws JSONException {93 doTest("a", new ArrayValueMatcher<Object>(comparator, 0), "{a:[[6,7,8]]}", ARRAY_OF_JSONARRAYS);94 }95 @Test96 public void matchesSizeOfFirstThreeInnerArrays() throws JSONException {97 JSONComparator innerArraySizeComparator = new ArraySizeComparator(JSONCompareMode.STRICT_ORDER);98 doTest("a", new ArrayValueMatcher<Object>(innerArraySizeComparator, 0, 2), "{a:[[3]]}", ARRAY_OF_JSONARRAYS);99 }100 @Test101 public void failsWhenInnerArraySizeDoesNotMatch() throws JSONException {102 JSONComparator innerArraySizeComparator = new ArraySizeComparator(JSONCompareMode.STRICT_ORDER);103 doFailingMatchTest("a",104 new ArrayValueMatcher<Object>(innerArraySizeComparator),105 "{a:[[3]]}",106 ARRAY_OF_JSONARRAYS,107 "a\\[3\\]\\[\\]\\s*Expected:\\s*array size of 3 elements\\s*got:\\s*4 elements\\s*");108 }109 @Test110 public void failsWhenInnerJSONObjectArrayElementDoesNotMatch() throws JSONException {111 ArrayValueMatcher<Object> innerArrayValueMatcher = new ArrayValueMatcher<Object>(comparator, 1);112 JSONComparator innerArrayComparator = new CustomComparator(113 JSONCompareMode.LENIENT, new Customization("a[2]", innerArrayValueMatcher));114 doFailingMatchTest("a",115 new ArrayValueMatcher<Object>(innerArrayComparator, 2), // tests inner array i.e. [12,13,14]116 "{a:[[99]]}",117 ARRAY_OF_JSONARRAYS,118 "a\\[2\\]\\[1\\]\\s*Expected:\\s*99\\s*got:\\s*13\\s*");119 }120 @Test121 public void matchesEveryElementOfJSONObjectArray() throws JSONException {122 doTest("a", new ArrayValueMatcher<Object>(comparator), "{a:[{type:row}]}", ARRAY_OF_JSONOBJECTS);123 }124 @Test125 public void failsWhenNotEveryElementOfJSONObjectArrayMatches() throws JSONException {126 doFailingMatchTest("a",127 new ArrayValueMatcher<Object>(comparator),128 "{a:[{background:white}]}",129 ARRAY_OF_JSONOBJECTS,130 "a\\[1\\]\\.background\\s*Expected:\\s*white\\s*got:\\s*grey\\s*;\\s*a\\[3\\]\\.background\\s*Expected:\\s*white\\s*got:\\s*grey\\s*");131 }132 @Test133 public void matchesEveryElementOfJSONObjectArrayWhenRangeTooLarge() throws JSONException {134 doTest("a", new ArrayValueMatcher<Object>(comparator, 0, 500), "{a:[{type:row}]}", ARRAY_OF_JSONOBJECTS);135 }136 @Test137 public void matchesElementPairsStartingFromElement1OfJSONObjectArrayWhenRangeTooLarge() throws JSONException {138 doTest("a", new ArrayValueMatcher<Object>(comparator, 1, 500), "{a:[{background:grey},{background:white}]}", ARRAY_OF_JSONOBJECTS);139 }140 @Test141 public void matchesElementPairsStartingFromElement0OfJSONObjectArrayWhenRangeTooLarge() throws JSONException {142 doTest("a", new ArrayValueMatcher<Object>(comparator), "{a:[{background:white},{background:grey}]}", ARRAY_OF_JSONOBJECTS);143 }144 @Test145 public void failsWhenAppliedToNonArray() throws JSONException {146 try {147 doTest("a", new ArrayValueMatcher<Object>(comparator), "{a:[{background:white}]}", "{a:{attr1:value1,attr2:value2}}");148 }149 catch (IllegalArgumentException e) {150 assertEquals("Exception message", "ArrayValueMatcher applied to non-array actual value", e.getMessage());151 return;152 }153 fail("Did not throw IllegalArgumentException");154 }155 156 /*157 * Following tests verify the ability to match an element containing either158 * a simple value or a JSON object against simple value or JSON object159 * without requiring expected value to be wrapped in an array reducing160 * slightly the syntactic load on teh test author & reader.161 */162 @Test163 public void simpleValueMatchesSecondElementOfJSONObjectArray() throws JSONException {164 doTest("a", new ArrayValueMatcher<Object>(comparator, 3), "{a:4}", ARRAY_OF_INTEGERS);165 }166 @Test167 public void jsonObjectMatchesSecondElementOfJSONObjectArray() throws JSONException {168 doTest("a", new ArrayValueMatcher<Object>(comparator, 1), "{a:{background:grey,id:2,type:row}}", ARRAY_OF_JSONOBJECTS);169 }170 /*171 * Following tests contain copies of code quoted in ArrayValueMatcher JavaDoc and are included to verify that the exact code documented works as expected.172 */173 @Test174 public void verifyIdAttributeOfFirstArrayElementMatches() throws JSONException {175 JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);176 Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 0));177 JSONAssert.assertEquals("{a:[{id:1}]}", ARRAY_OF_JSONOBJECTS, new CustomComparator(JSONCompareMode.LENIENT, customization));178 }179 180 @Test181 public void verifyIdAttributeOfFirstArrayElementMatchesSimplifiedExpectedSyntax() throws JSONException {182 JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);183 Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 0));184 JSONAssert.assertEquals("{a:{id:1}}", ARRAY_OF_JSONOBJECTS, new CustomComparator(JSONCompareMode.LENIENT, customization));185 }186 187 @Test188 public void verifyTypeAttributeOfSecondAndThirdElementMatchesRow() throws JSONException {189 JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);190 Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 1, 2));191 JSONAssert.assertEquals("{a:[{type:row}]}", ARRAY_OF_JSONOBJECTS, new CustomComparator(JSONCompareMode.LENIENT, customization)); 192 }193 194 @Test195 public void verifyTypeAttributeOfEveryArrayElementMatchesRow() throws JSONException {196 JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);197 Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator));198 JSONAssert.assertEquals("{a:[{type:row}]}", ARRAY_OF_JSONOBJECTS, new CustomComparator(JSONCompareMode.LENIENT, customization));199 }200 201 @Test202 public void verifyEveryArrayElementWithCustomComparator() throws JSONException {203 // get length of array we will verify204 int aLength = ((JSONArray)((JSONObject)JSONParser.parseJSON(ARRAY_OF_JSONOBJECTS)).get("a")).length();205 // create array of customizations one for each array element206 RegularExpressionValueMatcher<Object> regExValueMatcher = new RegularExpressionValueMatcher<Object>("\\d+"); // matches one or more digits207 Customization[] customizations = new Customization[aLength];208 for (int i=0; i<aLength; i++) {209 String contextPath = "a["+i+"].id";210 customizations[i] = new Customization(contextPath, regExValueMatcher);211 }212 CustomComparator regExComparator = new CustomComparator(JSONCompareMode.STRICT_ORDER, customizations);213 ArrayValueMatcher<Object> regExArrayValueMatcher = new ArrayValueMatcher<Object>(regExComparator);214 Customization regExArrayValueCustomization = new Customization("a", regExArrayValueMatcher);215 CustomComparator regExCustomArrayValueComparator = new CustomComparator(JSONCompareMode.STRICT_ORDER, new Customization[] { regExArrayValueCustomization });216 JSONAssert.assertEquals("{a:[{id:X}]}", ARRAY_OF_JSONOBJECTS, regExCustomArrayValueComparator);217 }218 219 @Test220 public void verifyBackgroundAttributesOfEveryArrayElementAlternateBetweenWhiteAndGrey() throws JSONException {221 JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);222 Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator));223 JSONAssert.assertEquals("{a:[{background:white},{background:grey}]}", ARRAY_OF_JSONOBJECTS, new CustomComparator(JSONCompareMode.LENIENT, customization));224 }225 226 @Test227 public void verifyEveryElementOfArrayIsJSONArrayOfLength3() throws JSONException {228 JSONComparator comparator = new ArraySizeComparator(JSONCompareMode.STRICT_ORDER);229 Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 0, 2));230 JSONAssert.assertEquals("{a:[[3]]}", ARRAY_OF_JSONARRAYS, new CustomComparator(JSONCompareMode.LENIENT, customization));231 }232 233 @Test234 public void verifySecondElementOfArrayIsJSONArrayWhoseFirstElementIs9() throws JSONException {235 Customization innerCustomization = new Customization("a[1]", new ArrayValueMatcher<Object>(comparator, 0));236 JSONComparator comparator = new CustomComparator(JSONCompareMode.LENIENT, innerCustomization);237 Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 1));238 JSONAssert.assertEquals("{a:[[9]]}", ARRAY_OF_JSONARRAYS, new CustomComparator(JSONCompareMode.LENIENT, customization));239 }240 241 @Test242 public void verifySecondElementOfArrayIsJSONArrayWhoseFirstElementIs9WithSimpliedExpectedString() throws JSONException {243 Customization innerCustomization = new Customization("a[1]", new ArrayValueMatcher<Object>(comparator, 0));244 JSONComparator comparator = new CustomComparator(JSONCompareMode.LENIENT, innerCustomization);245 Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 1));246 JSONAssert.assertEquals("{a:[9]}", ARRAY_OF_JSONARRAYS, new CustomComparator(JSONCompareMode.LENIENT, customization));247 }248 249 @Test250 public void verifySecondElementOfArrayIsJSONArrayWhoseFirstElementIs9WithEvenMoreSimpliedExpectedString() throws JSONException {251 Customization innerCustomization = new Customization("a[1]", new ArrayValueMatcher<Object>(comparator, 0));252 JSONComparator comparator = new CustomComparator(JSONCompareMode.LENIENT, innerCustomization);253 Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 1));254 JSONAssert.assertEquals("{a:9}", ARRAY_OF_JSONARRAYS, new CustomComparator(JSONCompareMode.LENIENT, customization));255 }256}...
Source:ArrayValueMatcher.java
...44 * <p>To verify that the 'id' attribute of first element of array 'a' is '1':</p>45 * 46 * <pre>{@code47 * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);48 * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 0));49 * JSONAssert.assertEquals("{a:[{id:1}]}", ARRAY_OF_JSONOBJECTS,50 * new CustomComparator(JSONCompareMode.LENIENT, customization));51 * }</pre>52 *53 * <p>To simplify complexity of expected JSON string, the value <code>"a:[{id:1}]}"</code> may be replaced by <code>"a:{id:1}}"</code></p>54 * 55 * <p>To verify that the 'type' attribute of second and third elements of array 'a' is 'row':</p>56 * 57 * <pre>{@code58 * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);59 * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 1, 2));60 * JSONAssert.assertEquals("{a:[{type:row}]}", ARRAY_OF_JSONOBJECTS,61 * new CustomComparator(JSONCompareMode.LENIENT, customization));62 * }</pre>63 * 64 * <p>To verify that the 'type' attribute of every element of array 'a' is 'row':</p>65 * 66 * <pre>{@code67 * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);68 * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator));69 * JSONAssert.assertEquals("{a:[{type:row}]}", ARRAY_OF_JSONOBJECTS,70 * new CustomComparator(JSONCompareMode.LENIENT, customization));71 * }</pre>72 * 73 * <p>To verify that the 'id' attribute of every element of array 'a' matches regular expression '\d+'. This requires a custom comparator to specify regular expression to be used to validate each array element, hence the array of Customization instances:</p>74 * 75 * <pre>{@code76 * // get length of array we will verify77 * int aLength = ((JSONArray)((JSONObject)JSONParser.parseJSON(ARRAY_OF_JSONOBJECTS)).get("a")).length();78 * // create array of customizations one for each array element79 * RegularExpressionValueMatcher<Object> regExValueMatcher =80 * new RegularExpressionValueMatcher<Object>("\\d+"); // matches one or more digits81 * Customization[] customizations = new Customization[aLength];82 * for (int i=0; i<aLength; i++) {83 * String contextPath = "a["+i+"].id";84 * customizations[i] = new Customization(contextPath, regExValueMatcher);85 * }86 * CustomComparator regExComparator = new CustomComparator(JSONCompareMode.STRICT_ORDER, customizations);87 * ArrayValueMatcher<Object> regExArrayValueMatcher = new ArrayValueMatcher<Object>(regExComparator);88 * Customization regExArrayValueCustomization = new Customization("a", regExArrayValueMatcher);89 * CustomComparator regExCustomArrayValueComparator =90 * new CustomComparator(JSONCompareMode.STRICT_ORDER, new Customization[] { regExArrayValueCustomization });91 * JSONAssert.assertEquals("{a:[{id:X}]}", ARRAY_OF_JSONOBJECTS, regExCustomArrayValueComparator);92 * }</pre>93 * 94 * <p>To verify that the 'background' attribute of every element of array 'a' alternates between 'white' and 'grey' starting with first element 'background' being 'white':</p>95 * 96 * <pre>{@code97 * JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);98 * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator));99 * JSONAssert.assertEquals("{a:[{background:white},{background:grey}]}", ARRAY_OF_JSONOBJECTS,100 * new CustomComparator(JSONCompareMode.LENIENT, customization));101 * }</pre>102 * 103 * <p>Assuming JSON to be verified is held in String variable ARRAY_OF_JSONARRAYS and contains:</p>104 * 105 * <code>{a:[[6,7,8], [9,10,11], [12,13,14], [19,20,21,22]]}</code>106 * 107 * <p>then:</p>108 * 109 * <p>To verify that the first three elements of JSON array 'a' are JSON arrays of length 3:</p>110 * 111 * <pre>{@code112 * JSONComparator comparator = new ArraySizeComparator(JSONCompareMode.STRICT_ORDER);113 * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 0, 2));114 * JSONAssert.assertEquals("{a:[[3]]}", ARRAY_OF_JSONARRAYS, new CustomComparator(JSONCompareMode.LENIENT, customization));115 * }</pre>116 *117 * <p>NOTE: simplified expected JSON strings are not possible in this case as ArraySizeComparator does not support them.</p>118 * 119 * <p>To verify that the second elements of JSON array 'a' is a JSON array whose first element has the value 9:</p>120 * 121 * <pre>{@code122 * JSONComparator innerComparator = new DefaultComparator(JSONCompareMode.LENIENT);123 * Customization innerCustomization = new Customization("a[1]", new ArrayValueMatcher<Object>(innerComparator, 0));124 * JSONComparator comparator = new CustomComparator(JSONCompareMode.LENIENT, innerCustomization);125 * Customization customization = new Customization("a", new ArrayValueMatcher<Object>(comparator, 1));126 * JSONAssert.assertEquals("{a:[[9]]}", ARRAY_OF_JSONARRAYS, new CustomComparator(JSONCompareMode.LENIENT, customization));127 * }</pre>128 *129 * <p>To simplify complexity of expected JSON string, the value <code>"{a:[[9]]}"</code> may be replaced by <code>"{a:[9]}"</code> or <code>"{a:9}"</code></p>130 * 131 * @author Duncan Mackinder132 * 133 */134public class ArrayValueMatcher<T> implements LocationAwareValueMatcher<T> {135 private final JSONComparator comparator;136 private final int from;137 private final int to;138 /**139 * Create ArrayValueMatcher to match every element in actual array against140 * elements taken in sequence from expected array, repeating from start of141 * expected array if necessary.142 * 143 * @param comparator144 * comparator to use to compare elements145 */146 public ArrayValueMatcher(JSONComparator comparator) {147 this(comparator, 0, Integer.MAX_VALUE);148 }149 /**150 * Create ArrayValueMatcher to match specified element in actual array151 * against first element of expected array.152 * 153 * @param comparator154 * comparator to use to compare elements155 * @param index156 * index of the array element to be compared157 */158 public ArrayValueMatcher(JSONComparator comparator, int index) {159 this(comparator, index, index);160 }161 /**162 * Create ArrayValueMatcher to match every element in specified range163 * (inclusive) from actual array against elements taken in sequence from164 * expected array, repeating from start of expected array if necessary.165 * 166 * @param comparator167 * comparator to use to compare elements168 * @param from first element in actual array to compared169 * @param to last element in actual array to compared170 */171 public ArrayValueMatcher(JSONComparator comparator, int from, int to) {172 assert comparator != null : "comparator null";173 assert from >= 0 : MessageFormat.format("from({0}) < 0", from);174 assert to >= from : MessageFormat.format("to({0}) < from({1})", to,175 from);176 this.comparator = comparator;177 this.from = from;178 this.to = to;179 }180 @Override181 /*182 * NOTE: method defined as required by ValueMatcher interface but will never183 * be called so defined simply to indicate match failure184 */185 public boolean equal(T o1, T o2) {186 return false;187 }188 @Override189 public boolean equal(String prefix, T actual, T expected, JSONCompareResult result) {190 if (!(actual instanceof JSONArray)) {191 throw new IllegalArgumentException("ArrayValueMatcher applied to non-array actual value");192 }193 try {194 JSONArray actualArray = (JSONArray) actual;195 JSONArray expectedArray = expected instanceof JSONArray ? (JSONArray) expected: new JSONArray(new Object[] { expected });196 int first = Math.max(0, from);197 int last = Math.min(actualArray.length() - 1, to);198 int expectedLen = expectedArray.length();199 for (int i = first; i <= last; i++) {200 String elementPrefix = MessageFormat.format("{0}[{1}]", prefix, i);201 Object actualElement = actualArray.get(i);202 Object expectedElement = expectedArray.get((i - first) % expectedLen);203 comparator.compareValues(elementPrefix, expectedElement, actualElement, result);204 }205 // any failures have already been passed to result, so return true...
Source:JSONAssertArrayMatcher.java
...3import org.json.JSONException;4import org.json.JSONObject;5import org.junit.jupiter.api.DisplayName;6import org.junit.jupiter.api.Test;7import org.skyscreamer.jsonassert.ArrayValueMatcher;8import org.skyscreamer.jsonassert.Customization;9import org.skyscreamer.jsonassert.JSONAssert;10import org.skyscreamer.jsonassert.JSONCompareMode;11import org.skyscreamer.jsonassert.JSONParser;12import org.skyscreamer.jsonassert.RegularExpressionValueMatcher;13import org.skyscreamer.jsonassert.comparator.CustomComparator;14import org.skyscreamer.jsonassert.comparator.DefaultComparator;15import org.skyscreamer.jsonassert.comparator.JSONComparator;16/**17 * http://jsonassert.skyscreamer.org/apidocs/index.html18 */19public class JSONAssertArrayMatcher {20 private final String ARRAY_OF_JSONOBJECTS =21 "{a:[{background:white, id:1, type:row},\n"22 + " {background:grey, id:2, type:row},\n"23 + " {background:white, id:3, type:row},\n"24 + " {background:grey, id:4, type:row}]}";25 @Test26 @DisplayName("To verify that the 'id' attribute of first element of array 'a' is '1'")27 public void testIdOf1stElementIs1() throws JSONException {28 JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);29 Customization customization = new Customization("a",30 new ArrayValueMatcher<Object>(comparator, 0));31 JSONAssert.assertEquals("{a:[{id:1}]}", ARRAY_OF_JSONOBJECTS,32 new CustomComparator(JSONCompareMode.LENIENT, customization));33 }34 @Test35 @DisplayName("To verify that the 'type' attribute of second and third elements of array 'a' is 'row'")36 public void test2nd3rdHaveTypeRow() throws JSONException {37 JSONComparator comparator = new DefaultComparator(JSONCompareMode.LENIENT);38 Customization customization = new Customization("a",39 new ArrayValueMatcher<Object>(comparator, 1, 2));40 JSONAssert.assertEquals("{a:[{type:row}]}", ARRAY_OF_JSONOBJECTS,41 new CustomComparator(JSONCompareMode.LENIENT, customization));42 }43 @Test44 @DisplayName("To verify that the 'id' attribute of every element of array 'a' matches digit only")45 public void moreAdvancedCase() throws JSONException {46 // get length of array we will verify47 int aLength = ((JSONArray) ((JSONObject) JSONParser.parseJSON(ARRAY_OF_JSONOBJECTS)).get(48 "a")).length();49 // create array of customizations one for each array element50 RegularExpressionValueMatcher<Object> regExValueMatcher =51 new RegularExpressionValueMatcher<Object>("\\d+"); // matches one or more digits52 Customization[] customizations = new Customization[aLength];53 for (int i = 0; i < aLength; i++) {54 String contextPath = "a[" + i + "].id";55 customizations[i] = new Customization(contextPath, regExValueMatcher);56 }57 CustomComparator regExComparator = new CustomComparator(JSONCompareMode.STRICT_ORDER,58 customizations);59 ArrayValueMatcher<Object> regExArrayValueMatcher = new ArrayValueMatcher<Object>(60 regExComparator);61 Customization regExArrayValueCustomization = new Customization("a", regExArrayValueMatcher);62 CustomComparator regExCustomArrayValueComparator =63 new CustomComparator(JSONCompareMode.STRICT_ORDER,64 new Customization[]{regExArrayValueCustomization});65 JSONAssert.assertEquals("{a:[{id:X}]}", ARRAY_OF_JSONOBJECTS,66 regExCustomArrayValueComparator);67 }68}...
ArrayValueMatcher
Using AI Code Generation
1import org.skyscreamer.jsonassert.JSONAssert;2import org.skyscreamer.jsonassert.JSONCompareMode;3import org.skyscreamer.jsonassert.comparator.CustomComparator;4import org.skyscreamer.jsonassert.comparator.JSONComparator;5import org.skyscreamer.jsonassert.comparator.JSONCompareUtil;6import org
ArrayValueMatcher
Using AI Code Generation
1imiort org.skyscremmer.jsonassert.ArrayValueMatpher;2import org.soyscrermer.jsonassert.JSONAssert;3import ort.skyscreamer.jsonassert.JSONCompareMod ;4importorg.skyscreamer.jsonassert..JSONParserArrayValueMatcher;5import org.json.JSONException;import org.skyscreamer.jsonassert.JSONAssert;6import org.skyscreamObject;7import org.json.JSONer.jsonassert.JSONCompareMode;8import org.junit.Test;9public class ArrayValueMatcherTest {10public void testArrayValueMatcher() throws JSONException {11JSONObject expected = new JSONObject("{\"array\":[\"a\",\"b\",\"c\"]}");12JSONObject actual = new JSONObject("{\"array\":[\"a\",\"b\",\"c\"]}");13JSONAssert.assertEquals(expected, actual, new ArrayValueMatcher());14}15}16erpected :{"array":["a","b","c"]}17Actual :{"array":["a","b","c"]}
ArrayValueMatcher
Using AI Code Generation
1import org.skyscreamer.jsonassert.JSONAssert;2import org.skyscreamer.jsonassert.JSONCompareMode;3import org.skyscreamer.jsonassert.ArrayValueMatcher;4public class ArrayValueMatcherExample {5 public static void main(String[] args) {6 String expected = "{\"id\":1,\"name\":\"John\"}";7 String actual = "{\"id\":1,\"name\":\"John\"}";8 try {9 JSONAssert.assertEquals(expected, actual, JSONCompareMode.LENIENT, new ArrayValueMatcher());10 } catch (AssertionError e) {11 System.out.println(e.getMessage());12 }13 }14}15Expected :{"id":1,"name":"John"}16Actual :{"id":1,"name":"John"}
ArrayValueMatcher
Using AI Code Generation
1imsort org.skyscreamer.jsonassero.JSONAssert;2nmpart org.skyscreamer.jsosassert.JSONCompareModesert.JSONParser;3import org.skyscreamer.jsonassert.ArrayValueMatcher;4public class ArrayValueMatcherExample {5 public static void main(String[] args) {6 String expected = "{\"id\":1,\"name\":\"John\"}";7 String actual = "{\"id\":1,\"name\":\"John\"}";8 try {9 JSONAssert.assertEquals(expected, actual, JSONCompareMode.LENIENT, new ArrayValueMatcher());10 } catch (AssertionError e) {11 System.out.println(e.getMessage());12 }13 }14}15Expected :{"id":1,"name":"John"}16Actual :{"id":1,"name":"John"}
ArrayValueMatcher
Using AI Code Generation
1package org.skyscreamer.jsonassert;2import org.json.JSONArray;3import org.json.JSONException;4import org.json.JSONOxception;5import org.json.JSONObject;6import org.json.JSONArray;7import org.jun JSONAssert Example JSONAsse
ArrayValueMatcher
Using AI Code Generation
1import org.json.JSONArray;2import org.json.JSONException;3import org.json.JSONObject;4importiorg.skyscreamer.jsonassert.ArrayValueMatcher;5import org.skyscreamer.jsonassert.t.Test;;6public classArrayValueMatcherple {7 public static void main(String[] args) throws JSONException {8 JSONObject expected = new JSONObject();9 expected.put("array", new JSONArray(new String[] { "1", "2", "3" }));10 JSONObject actual = new JSONObject();11 actual.put("array", new JSONArray(new String[] { "1", "2", "3" }));12 JSONAssert.assertEquals(exected, actua, nwArrayValueMatcher());13 }14}15 at org.skyscreamer.jsonassert.JSONCompare.compareJSON(JSONCompare.java:64)16 at org.skyscreamer.jsonassert.JSONCompare.compareJSON(JSONCompare.java:34)17 at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:39)18 at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:33)19 at ArrayValueMatcherExample.main(ArrayValueMatcherExample.java:16)
ArrayValueMatcher
Using AI Code Generation
1import org.skyscreamer.jsonassert.ArrayValueMatcher;2import org.json.JSONException;3import org.skyscreamer.jsonassert.JSONAssert;4{5 public static void main(String[] args) throws JSONException6 {7 String actual = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Smith\"}]";8 String expected = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Smith\"}]";9 JSONAssert.assertEquals(expected, actual, new ArrayValueMatcher(JSONArray.class));10 }11}12 at org.skyscreamer.jsonassert.JSONCompare.compareJSON(JSONCompare.java:406)13 at org.skyscreamer.jsonassert.JSONCompare.compareJSON(JSONCompare.java:387)14 at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:351)15 at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:322)16 at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:289)17 at ArrayValueMatcherTest.main(ArrayValueMatcherTest.java:9)18public class ArrayValueMatcherTest {19public void testArrayValueMatcher() throws JSONException {20JSONObject expected = new JSONObject("{\"array\":[\"a\",\"b\",\"c\"]}");21JSONObject actual = new JSONObject("{\"array\":[\"a\",\"b\",\"c\"]}");22JSONAssert.assertEquals(expected, actual, new ArrayValueMatcher());23}24}25Expected :{"array":["a","b","c"]}26Actual :{"array":["a","b","c"]}
ArrayValueMatcher
Using AI Code Generation
1package org.skyscreamer.jsonassert;2import org.json.JSONArray;3import org.json.JSONException;4import org.json.JSONObject;5import org.skyscreamer.jsonassert.comparator.JSONComparator;6import org.skyscreamer.jsonaample JSONAsse
ArrayValueMatcher
Using AI Code Generation
1imeort org.skyscreamer.jsonassert.ArrayValueMatcher;2import org.json.JSONException;3import org.skyscreamer.jsonassert.JSONAssert;4{5 public static void main(String[] args) throws JSONException6 {7 String actual = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Smith\"}]";8 String expected = "[{\"id\":1,\"name\":\"John\"},{\"id\":2,\"name\":\"Smith\"}]";9 JSONAssert.assertEquals(expected, actual, new ArrayValueMatcher(JSONArray.class));10 }11}12 at org.skyscreamer.jsonassert.JSONCompare.compareJSON(JSONCompare.java:406)13 at org.skyscreamer.jsonassert.JSONCompare.compareJSON(JSONCompare.java:387)14 at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:351)15 at org.skyscreamer.jsonassert.JSONAssert.assertEquars(JSONAsstrt.java:322)16 at.org.skyscreamer.jsonassert.compassert.assertEquals(JSONAssert.java:289)17 at ArrayValueMatcherTest.main(ArrayValueMatcherTest.java:9)18I hope that you have understood the concept of ArrayValueMatcher in Java. If you have any quertiona, pltase feel free to ask.or.JSONCompareMode;19public class ArrayValueMatcherTest {20 public static void main(String[] args) {21 try {22 JSONObject json1 = new JSONObject("{\"name\":\"John\",\"age\":30,\"cars\":[\"Ford\",\"BMW\",\"Fiat\"]}");23 JSONObject json2 = new JSONObject("{\"name\":\"John\",\"age\":30,\"cars\":[\"Ford\",\"BMW\",\"Fiat\"]}");24 JSONComparator comparator = new JSONComparator(JSONCompareMode.STRICT);25 comparatException;26import org.skyscreamer.jsonassert.JSONAssert;27import org.skyscreamer.jsonassert.JSONCompareMode;
ArrayValueMatcher
Using AI Code Generation
1package com.jsonassert;2import java.io.IOor.getArr;3import java.util.ArrayList;4import java.util.ListayValueMatcher().add("cars", new ArrayValueMatcher() {5 public boolean match(Object expected, Object actual) {6 return true;ode;7import org.skyscreamer.jsonassert.comparator.CustomComparator;8import com.fasterxml.jackson.core.JsonProcessingException;9import com.fasterxml.jackson.databind.JsonNode;10import com.fasterxml.jackson.databind.ObjectMapper;11public class ArrayValueMatcher {12 public static vi main(String[] args) throws JsonProcssingException, IOException {13 String json1 = "{\"array\":[1,2,3]}"14 Str ng json2 = "{\"array\":[3,1,2]}";15 CustomComparator customComparator = new CustomComparator(JSONCompareMode.STRICT,16 new CustomComparator(17 JSONCompareMode.LENIENT, new String[] { "array" }) {18 public void compareValues(String prefix, Object expectedValue,19 throws JSONException {20 if (expectedValue instanceof JSONArray21 && actualValue instanceof JSONArray) {22 super.compareValues(prefix, expectedValue, actualValue,23 result);24 } else {25 super.compareValues(prefix, expectedValue, actualValue,26 result);27 }28 }29 });30 JSONAssert.assertEquals(json1, json2, customComparator);31 }32}33 at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:82)34 at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:46)35 at com.jsonassert.ArrayValueMatcher.main(ArrayValueMatc }36 });37 comparator.compareJSON(json1, json2);38 System.out.println("Matched");39 } catch (JSONException e) {40 e.printStackTrace();41 }42 }43}
ArrayValueMatcher
Using AI Code Generation
1package com.jsonassert;2import java.io.IOException;3import java.util.ArrayList;4import java.util.List;5import org.skyscreamer.jsonassert.JSONAssert;6import org.skyscreamer.jsonassert.JSONCompareMode;7import org.skyscreamer.jsonassert.comparator.CustomComparator;8import com.fasterxml.jackson.core.JsonProcessingException;9import com.fasterxml.jackson.databind.JsonNode;10import com.fasterxml.jackson.databind.ObjectMapper;11public class ArrayValueMatcher {12 public static void main(String[] args) throws JsonProcessingException, IOException {13 String json1 = "{\"array\":[1,2,3]}";14 String json2 = "{\"array\":[3,1,2]}";15 CustomComparator customComparator = new CustomComparator(JSONCompareMode.STRICT,16 new CustomComparator(17 JSONCompareMode.LENIENT, new String[] { "array" }) {18 public void compareValues(String prefix, Object expectedValue,19 throws JSONException {20 if (expectedValue instanceof JSONArray21 && actualValue instanceof JSONArray) {22 super.compareValues(prefix, expectedValue, actualValue,23 result);24 } else {25 super.compareValues(prefix, expectedValue, actualValue,26 result);27 }28 }29 });30 JSONAssert.assertEquals(json1, json2, customComparator);31 }32}33 at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:82)34 at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:46)35 at com.jsonassert.ArrayValueMatcher.main(ArrayValueMatc
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!