Tuesday, April 16, 2013

Java testing with json

I recently wanted to write jUnit tests where I needed to have pre-constructed json in the test.
This gets very messy:

private void testAPI() {
    String json = "{\"someobject\":" +
              "{" +
              "\"attr1\": 123," +
              "\"attr2\": {" +
              // getting tired yet? ...
              "\"anotherattr\": \"foobar\"" +
              "}" + 
              "}" + 
    // clear as mud, right?
    // test here...

This definitely was impeding the velocity of my test driven development progress.  Also, I felt like the next person who looks at this test is never going to want to maintain this test...

I know I have looked at a test and thought to myself, "too much scary syntax, why bother fixing it".

Well, after some quick googling, I found a solution that I like so far: http://www.adrianwalker.org/2011/12/java-multiline-string.html

This code provides the @Multiline java annotation and it takes the comment before a String declaration and shoves it into the string variable.

Now my code looks like this:

private void testAPI() {
   "someobject": {
       "attr1": 123,
       "attr2": {"anotherattr": "foobar"}
    @Multiline String json;
    // test here...

Do you think this look better?  I think so.

I was able to use this guys github to install the annotation in eclipse with minimal effort:

I don't think this should be used in production code, but I really like using it for test code.