Thursday, May 17, 2012

cannedhttp - Testing HTTP based webservices in Java

So, recently I've again been writing webservices using HTTP as the transport in Java, and after getting used to node.js land where it is so, so easy to test these kinds of webservices, I was longing for the same kind of compact, self-contained testing. So, I came up with cannedhttp, a small self-contained 'canned' webservice testing tool to help with testing webservices.

The idea is very simple, most requests, especially in unit-testing scenarios, always need to return the same content. So, why can't this just be done with static webservers? Well, the problem with using static webservers for this is that you need to be able to set the HTTP response code, the HTTP headers (such as Content-type) and so forth, and also the different HTTP verbs such as POST, PUT, DELETE. Normally, static webservers only support GET.

So canned-http takes a very simple approach to this problem - your file structure is your web service endpoints. All files have an HTTP verb as the suffix - such as .GET, .POST, .PUT etc. All files also have a very simple file structure allowing you to specify http response code, headers, and content.

In addition to this, it also gives you a very basic router API to add handlers to intercept requests, allowing you to check whether your code is actually sending the correct requests through. It also allows you to customise the response - giving you the ability to start doing some real testing around your webservice calls, while not being reliant on an external webserver at all. It also gives you predictability - seeing as at it's basic form, cannedhttp always returns the same content for the same request.

Here is a sample canned file, showing how you could do a SOAP response for example:

Placing this file in a subdirectory as /one/two/soap.GET, will allow you to test a SOAP webservice at /one/two/SOAP

Here is some code showing the basic router API:

So, there it is. Hopefully this can be of use to some of you. I know it's been helping me the past week or so. It really has sped up the development of webservice code for me - some of the stuff I haven't even tested against a "real" webservice - I've just followed the spec documents and used the examples in those and made sure I could parse them, right there in my unit tests.

1 comment:

  1. Nice work. I've been using Soap UI's Idea plugin to test this kind of thing, which sucks because your tests are external to the actual java project.  Definitely gonna try this out!

    ReplyDelete