Java Reference
In-Depth Information
replacing, and that's difficult to get right for complex logic. Here are some cons
of stubbing:
Stubs are often complex to write and need debugging themselves.
Stubs can be difficult to maintain because they're complex.
Stubs don't lend themselves well to fine-grained unit testing.
Each situation requires a different stubbing strategy.
In general, stubs are better adapted for replacing coarse-grained portions of code.
You usually use stubs to replace a full-blown external system such as a file sys-
tem, a connection to a server, a database, and so forth. Stubs can replace a method
call to a single class, but it's more difficult. (We demonstrate how to do this with
mock objects in chapter 7.)
6.2
Stubbing an HTTP connection
To demonstrate what stubs can do, let's build some stubs for a simple application that
opens an HTTP connection to a URL and reads its content. Figure 6.1 shows the sam-
ple application (limited to a WebClient.getContent method) opening an HTTP con-
nection to a remote web resource. The remote web resource is a servlet, which
generates an HTML response. The web resource in figure 6.1 is what we called the
“real code” in the stub definition.
Our goal in this chapter is to unit test the getContent method by stubbing the
remote web resource, as demonstrated in figure 6.2. You replace the servlet web
resource with the stub, a simple HTML page returning whatever you need for the
TestWebClient test case. This approach allows you to test the getContent method
independently of the implementation of the web resource (which in turn could call
several other objects down the execution chain, possibly down to a database).
The important point to notice with stubbing is that we didn't modify getContent
to accept the stub. The change is transparent to the application under test. In order to
allow stubbing, the target code needs to have a well-defined interface and allow plug-
ging in of different implementations (a stub, in our case). In the figure 6.1 example,
the interface is the public abstract class java.net.URLConnection , which cleanly iso-
lates the implementation of the page from its caller.
Figure 6.1 The sample application opens an HTTP connection to a remote web resource. The web
resource is the “real code” in the stub definition.
 
 
 
 
 
 
Search WWH ::




Custom Search