0

I am trying to learn JUnit and I have been practicing it for some time now I have a problem in comparing 2 objects. That is think of it as JSON objects. I am using GSON for this purpose

For example, I have a JSON string and I have converted it into an object and I have another JSON object which will be exactly the same, now when I write assertEquals for these 2 objects it's returning something like

java.lang.AssertionError:   
  Expected :Data@2ret9593
  Actual   :Data@7647qe21

As they are JSON objects the order of the key-value pairs may differ but I want it to check them and return the result if they are equal or not and ignore some fields whose values are not considered but the field is important like timestamp or dynamically generated id etc.

It's not just about equal method What I was trying here I to compare 2 JSON strings and ignore some fields that are dynamically allocated while testing

For example:

{"name": "ray", "age": "20"} == {"age": "20", "name": "ray", "timestamp": 03:10:54}

Is there any way to achieve what I want?

Srikar
  • 351
  • 5
  • 16

1 Answers1

3

Rather than deserialising JSON into an object to facilitate comparison you could use JSONAssert to facilitate meaningful 'JSON comparison' in your test cases.

For example:

String expected = "{"name": "ray", "age": "20"}";
String actual = "{"age": "20", "name": "ray"}"
JSONAssert.assertEquals(expected, actual, false);

In this example strict has been set to false, this instructs JSONAssert to forgive reordering.

To use JSONAssert just download the JAR or - if using Maven - add the following to your project's pom.xml:

<dependency>
    <groupId>org.skyscreamer</groupId>
    <artifactId>jsonassert</artifactId>
    <version>1.5.0</version>
    <scope>test</scope>
</dependency>

And add assertions like this:

JSONAssert.assertEquals(expectedJSONString, actualJSON, strictMode);

More examples in the cookbook.

glytching
  • 44,936
  • 9
  • 114
  • 120
  • hey, glytching is there any way to ignore some fields if some conditions are met and check those fields if the condition fails. – Srikar Jan 22 '18 at 09:30
  • You could perhaps provide your own implementation of jsonasserts' `DefaultComparator`. FWIW, there's a lengthy discussion of partial assertions on [this JSONAssert issue](https://github.com/skyscreamer/JSONassert/issues/15). – glytching Jan 22 '18 at 09:45