Java Reference
In-Depth Information
return content.toString();
}
}
We start B by opening an HTTP connection using the HttpURLConnection class. We
then read the stream content until there's nothing more to read C . If an error
occurs, we return null D . One might argue that a better implementation should
throw an exception. But for testing purposes, returning null is fine.
6.2.1
Choosing a stubbing solution
There are two possible scenarios in the example application: the remote web server
(see figure 6.1) could be located outside the development platform (such as on a part-
ner site), or it could be part of the platform where you deploy the application. But in
both cases, you need to introduce a server into your development platform in order to
be able to unit test the WebClient class. One relatively easy solution would be to install
an Apache test server and drop some test web pages in its document root. This is a typ-
ical, widely used stubbing solution.
But it has several drawbacks, listed in table 6.1.
Table 6.1
Drawbacks of the chosen stubbing solution
Drawback
Explanation
Reliance on the environment
You need to be sure the full environment is up and running before
the test starts. If the web server is down and you execute the test,
it'll fail and you'll spend time debugging the failure. You'll discover
that the code is working fine and it's only a setup issue generating
a false failure. When you're unit testing, it's important to be able to
control as much as possible of the environment in which the tests
execute, such that test results are reproducible.
Separated test logic
The test logic is scattered in two separate locations: in the JUnit
test case and in the test web page. You need to keep both types of
resources in sync for the tests to succeed.
Difficult tests to automate
Automating the execution of the tests is difficult because it
involves deploying the web pages on the web server, starting the
web server, and then running the unit tests.
Fortunately, an easier solution exists using an embedded web server. Because we're
testing in Java, the easiest solution is to use a Java web server that you can embed in
the test case. You can use the free and open source Jetty server for this exact purpose.
In this topic, we use Jetty to set up our stubs. For more information about Jetty, visit
http://www.eclipse.org/jetty/.
We use Jetty because it's fast (important when running tests), it's lightweight, and
your test cases can programmatically control it. In addition, Jetty is a very good web,
servlet, and JSP container that you can use in production. You seldom need this for
most tests, but it's always nice to use best-of-breed technology.
 
 
 
 
 
Search WWH ::




Custom Search