Java Reference
In-Depth Information
13.7
Testing services with HttpClient
The idea behind testing the application services layer separately is to validate each ser-
vice independently from
HTML
, JavaScript, and
DOM
and how the application uses
the data. An application calls a service from JavaScript through the
XMLHttpRequest
object. Here, we use
XMLHttpRequest
to refer to the standard JavaScript
XMLHttp-
Request
object and to the Microsoft ActiveX
XMLHTTP
objects
Microsoft.XMLHTTP
and
Msxml2.XMLHTTP
. Our goal is to emulate an
XMLHttpRequest
object by using
HTTP
as the transport mechanism and
XML
and
JSON
as example data formats. We
use the Apache Commons HttpClient to provide
HTTP
support, Java's built-in
XML
support, and jslint4java to check that
JSON
documents are well formed.
13.7.1
Calling an XML service
To simplify this example, we've made the chapter's example webapp directory an
IIS
virtual directory so that we can run the unit tests from Ant locally. A production Ant
build would start and stop a web container like Jetty around the unit test invocations.
Our first
XML
service test in listing 13.10 makes sure that we're getting back from the
server the expected
XML
document. A second test validates the document.
Listing 13.10
An XML service test
@Test
public void testGetXmlBasicCheck() throws IOException {
HttpClient httpClient = new HttpClient();
GetMethod get = new GetMethod(
String responseString;
try {
httpClient.executeMethod(get);
InputStream input = get.getResponseBodyAsStream();
responseString = IOUtils.toString(input, "UTF-8");
} finally {
get.releaseConnection();
}
Assert.assertTrue(responseString, responseString.startsWith(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
// more...
}
The test starts by creating an Apache Commons
HttpClient
b
and defining the
HTTP
GET
method
C
with a
URL
for our
XML
document fixture. The
URL
specified in
the
GetMethod
constructor is application specific and must include parameters if
appropriate for a given test. The test then executes the
HTTP
GET
method
D
and
reads the data back from the server. Note the use of the Apache Commons
IO
API
IOUtils.toString
to read the response stream in a string as a one-liner
E
. The code
does this synchronously, unlike a standard Ajax application. We then guarantee that
HttpClient
resources are freed by calling
releaseConnection
from a
finally
block
F
. We can now check that the data from the server is as expected. For this first test, all
B
C
D
E
F
G