damirarh / damirscorner-utterances

utteranc.es comments for https://damirscorner.com
0 stars 0 forks source link

blog/posts/20220520-ComparingJsonStringsInUnitTests #149

Open utterances-bot opened 4 months ago

utterances-bot commented 4 months ago

Comparing JSON strings in unit tests | Damir's Corner

https://www.damirscorner.com/blog/posts/20220520-ComparingJsonStringsInUnitTests.html

fysicus commented 4 months ago

Good morning,

I follow your tutorial to write a unit test, for JSON validation, but I keep on running into a couple of issues.

I'm developping an application in .NET 4.8, this application calls a web service. The we service returns a JSON formatted response.

It's a relatively complex JSON, relatively big (> 200 000 lines on average) and it contains a lot of nested structures.

Some of these structures repeat, even with the same date, but... the numeric format isn't always consistent. In some cases (even when the data which is shown is the same) some fields are given in int, to be repeated later in the response as a float.

   {
       "result": [
           {
                "In": {
                    "consumer": {
                       "tax": 65.00
                    }
                },
                "Out": {
                    "consumer": {
                       "tax": 65
                    },
                }
           }
       ]
   }

This causes problem with the validation, because when I run the comparison in some cases an int is expected, but one of the other records has a float... and vice versa.

I originally attempted to solve this by using duplicated of certain classes. One with the numerical fields defined as int, the other as float, but unfortunately there are also cases in which the data consists of a mix of int and float.

Been googling all day, but I haven't been able to find a workable solution for the problem.

Perhaps you are aware of one?

lateapexearlyspeed commented 3 months ago

Hi @fysicus , not sure exactly about your requirement but guess what you would like is to treat 65.00 (float) equals to 65 (int) ? If that is case, can you try this Xunit json assertion package which considers this situation because this (int/float) case is defined in "Json Schema spec" and this library implements it, thanks: https://github.com/lateapexearlyspeed/Lateapexearlyspeed.JsonSchema

For your example, this assertion will pass:

string actualJson = """
    {
        "consumer": {
           "tax": 65.00
        }
    }
    """;

string expectedJson = """
    {
        "consumer": {
           "tax": 65
        }
    }
    """;

JsonAssertion.Equivalent(expectedJson, actualJson);

Any feedback is appreciated :)