views:

57

answers:

2

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.

Therefore, is there a better way of doing this? Surely there must be? Does anyone know of any good literature in regard to this specific case (doesn't have to be json, but you know what I mean)?

Grateful for all help.

+2  A: 

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.

mamoo
+3  A: 

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.

Chris J
This is a really nifty solution, and now that you've said it I'm sort of beating myself up for not thinking of it myself. Thank you!
Banang