1 package org.onap.vid.testUtils;
3 import org.json.JSONArray;
4 import org.json.JSONObject;
5 import org.junit.Assert;
7 import java.util.Iterator;
9 import static fj.parser.Parser.fail;
12 * Created by Oren on 6/7/17.
14 public class TestUtils {
17 * The method compares between two jsons. the function assert that the actual object does not reduce or change the functionallity/parsing of the expected json.
18 * This means that if the expected JSON has a key which is null or the JSON doesn't have a key which contained in the expected JSON the assert will succeed and the will pass.
19 * For example : For JSON expected = {a:null} and actual {a:3} the test will pass
20 * Other example : For JSON expected = {a:3} and actual {a:null} the test will fail
22 * @param expected JSON
25 public static void assertJsonStringEqualsIgnoreNulls(String expected, String actual) {
26 if (expected == null || expected == JSONObject.NULL) {return;}
28 JSONObject expectedJSON = new JSONObject(expected);
29 JSONObject actualJSON = new JSONObject(actual);
30 Iterator<?> keys = expectedJSON.keys();
32 while( keys.hasNext() ) {
33 String key = (String)keys.next();
34 Object expectedValue = expectedJSON.get(key);
35 if (expectedValue == JSONObject.NULL){
39 Object actualValue = actualJSON.get(key);
41 if (expectedValue instanceof JSONObject) {
42 String expectedVal = expectedValue.toString();
43 String actualVal = actualValue.toString();
44 assertJsonStringEqualsIgnoreNulls(expectedVal, actualVal);
46 else if (expectedValue instanceof JSONArray) {
47 if (actualValue instanceof JSONArray) {
48 JSONArray expectedJSONArray = (JSONArray)expectedValue;
49 JSONArray actualJSONArray = (JSONArray)actualValue;
50 for (int i = 0; i < expectedJSONArray.length(); i++) {
51 String expectedItem = expectedJSONArray.get(i).toString();
52 String actualItem = actualJSONArray.get(i).toString();
53 if (expectedValue instanceof JSONObject)
54 assertJsonStringEqualsIgnoreNulls(expectedItem, actualItem);
58 fail("expected: " + expectedValue + " got:" + actualValue);
62 Assert.assertEquals(expectedValue, actualValue);