Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing JSON output module, best practices

I am currently working on a module that takes one of our business objects and returns a json representation of that object to the caller. Due to limitations in our environment I am unable to use any existing json writer, so I have written my own, which is then used by the business object writer to serialize my objects. The json writer is tested in a way similar to this

@Test
public void writeEmptyArrayTest() 
{
   String expected = "[  ]";
   writer.array().endArray();
   assertEquals(expected, writer.toString());
}

which is only manageable because of the small output each instruction produces, even though I keep feeling there must be a better way.

The problem I am now facing is writing tests for the object writer module, where the output is much larger and much less manageable. The risk of spelling mistakes in the expected strings mucking up my tests seem too great, and writing code in this fashion seems both silly and unmanageable in a long term perspective. I keep feeling like I want to write tests to ensure that my tests are behaving correctly, and this feeling worries me.

What is a better way of doing this?

like image 253
Mia Clarke Avatar asked Apr 22 '10 09:04

Mia Clarke


2 Answers

Technically the environment in which you are deploying your code is not the same as the environment in which you are developing it so I would use an existing JSON reader/writer to test the one you have created. If you are using maven, you can even set the scope of the JSON package you choose to use to be "test" so it will not be included in the actual build.

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20090911</version>
  <scope>test</scope>
</dependency>

Alternatively, you can have your unit test inherit from your JSON writer. By inheriting, you can test all the protected and private internal bits instead of checking the actual String output.

like image 80
Chris J Avatar answered Nov 10 '22 07:11

Chris J


Since you cannot use external libraries in your server-side code, probably a better approach would be to limit the api unit-tests to the essential: - Test primitive object serialization - Test array serialization - Test special characters serialization - ...

And then move part of the tests to the client side (using a JSON parser to ensure that at least your JSON is valid). Once you find a bug on the browser scripts execution, fix it and write a related unit-test to ensure that it doesn't show up again in the future releases.

like image 22
mamoo Avatar answered Nov 10 '22 06:11

mamoo