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:

  1. @Test
  2. private void testAPI() {
  3. String json = "{\"someobject\":" +
  4. "{" +
  5. "\"attr1\": 123," +
  6. "\"attr2\": {" +
  7. // getting tired yet? ...
  8. "\"anotherattr\": \"foobar\"" +
  9. "}" +
  10. "}" +
  11. "}";
  12. // clear as mud, right?
  13. // 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:

  1. @Test
  2. private void testAPI() {
  3. /**
  4. {
  5. "someobject": {
  6. "attr1": 123,
  7. "attr2": {"anotherattr": "foobar"}
  8. }
  9. }
  10. */
  11. @Multiline String json;
  12. // 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:
https://github.com/benelog/multiline

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

No comments:

Post a Comment