views:

221

answers:

1

Using Restlet I have created a router for my Java application.

From using curl, I know that each of the different GET, POST & DELETE requests work for each of the URIs and return the correct JSON response.

I'm wanting to set-up JUnit tests for each of the URI's to make the testing process easier. However, I'm not to sure the best way to make the request to each of the URIs in order to get the JSON response which I can then compare to make sure the results are as expected. Any thoughts on how to do this?

+1  A: 

You could just use a Restlet Client to make requests, then check each response and its representation.

For example:

Client client = new Client(Protocol.HTTP);
Request request = new Request(Method.GET, resourceRef);
Response response = client.handle(request);

assert response.getStatus().getCode() == 200;
assert response.isEntityAvailable();
assert response.getEntity().getMediaType().equals(MediaType.TEXT_HTML);

// Representation.getText() empties the InputStream, so we need to store the text in a variable
String text = response.getEntity().getText();
assert text.contains("search string");
assert text.contains("another search string");

I'm actually not that familiar with JUnit, assert, or unit testing in general, so I apologize if there's something off with my example. Hopefully it still illustrates a possible approach to testing.

Good luck!

Avi Flax
That was great. With assert it's assertTrue(...) for anyone else using the example, but perfect apart from that. Thanks
Lee
My pleasure, glad to help!BTW I recommend you try Groovy for this sort of thing — it makes the tests more concise. It's especially great that it has getter and setter shortcuts, and == means value equality.So instead of response.getEntity().getMediaType().equals(MediaType.TEXT_HTML) you can write response.entity.mediaType == MediaType.TEXT_HTML.HTH!
Avi Flax