1

I'm building a library, that takes a JSON string in and formats it according to template and specification, selected by the user.

I've recently started on writing Unit Tests for this library, and found that creating data I can assert against in some cases takes a lot of code, and in most cases makes the tests hard to read.

Just as an example of what the package does:

Input json:

{
   "id": 1,
   "name": "abc",
   "barId": 5
}

Output json:

{
   "href": "/foo/1",
   "name": "abc",
   "_children": [
      "bar": {
         "href": "/bar/5"
      }
   ]
}

So the parsed json can potentially be deeply nested, based on user configuration.

For now I've build a generator that uses Newtonsoft.Json to generate the objects to assert against, but all of that work got me thinking if there maybe is a better way to do it.

Some of the test I need to do is for example:

  • checking if the returned json contains "_children" when it should
  • if the href is empty, null or not there at all
  • if the properties are passed through properly
  • if the children have their properties passed through properly
  • all the variations based on the configuration.

So, back to the question is there some clean way to perform this kind of asserts? Is there a faster way to build the expected json, other than building it by hand?

fiji3300
  • 103
  • 7

1 Answers1

1

For me your are not creating a "fomatter" but a "JSON generator" since is not just changing the spaces, tabs, brackets, etc. is generating new content from the input.

All tests are about "for this input what is the expected output"

So create enough input files that cover all your rules/scenarios and the relevant expected output files.

Then with that an any XUnit/Nunit any of your choice.

string input = loadJson("sample1.json") ;
string expected = loadJson("sample1_expected.json") ;

string generated = generateJson(input) ;

if(compareJsonFiles(generated,expected)== 0)
    // files are equal
else 
    // something went wrong

My code is very generic because your question is conceptual, and you did not provide any code.

The loadJson could involve parsing or not, that dependes on how your generator is implemented - How can I parse JSON with C#?

To compareJsonFiles you can check these answers Find and return JSON differences using newtonsoft in C#?

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99