Java Reference
In-Depth Information
Figure 6.5
Result of executing TestWebClient1
(which uses the StubHttpURLConnection )
6.4.3
Running the test
Let's run the TestWebClient1 test, which uses the StubHttpURLConnection . Figure 6.5
shows the result of the execution of the test in Eclipse.
As you can see, it's much easier to stub the connection than to stub the web
resource. This approach doesn't bring the same level of testing (you aren't perform-
ing integration tests), but it enables you to more easily write a focused unit test for the
WebClient logic.
6.5
Summary
In this chapter, we demonstrated how using a stub has helped us unit test code access-
ing a remote web server using the Java HttpURLConnection API . In particular, we
showed how to stub the remote web server by using the open source Jetty server. Jetty's
embeddable nature lets you concentrate on stubbing only the Jetty HTTP request han-
dler, instead of having to stub the whole container. We also demonstrated a more
lightweight solution by stubbing the Java HttpURLConnection class.
The next chapter demonstrates a technique called mock objects that allows fine-
grained unit testing, which is completely generic, and (best of all) forces you to write
good code. Although stubs are very useful in some cases, some consider them more a
vestige of the past, when the consensus was that tests should be a separate activity and
shouldn't modify existing code. The new mock objects strategy not only allows modifi-
cation of code but favors it. Using mock objects is more than a unit testing strategy;
it's a completely new way of writing code.
 
 
 
 
 
 
Search WWH ::




Custom Search