Java Reference
In-Depth Information
At
B
, we use a mock logger that implements the
Log
interface but does nothing. Next,
we create a
MockConfiguration
instance
C
and set it up to return a given
SQL
query
when
Configuration.getSQL
is called. Finally, we create the instance of
Default-
AccountManager
D
that we test, passing to it the
Log
and
Configuration
instances.
We've been able to completely control our logging and configuration behavior
from outside the code to test, in the test code. As a result, our code is more flexible
and allows for any logging and configuration implementation to be used. You'll see
more of these code refactorings in this chapter and later ones.
One last point to note is that if you write your test first, you'll automatically design
your code to be flexible. Flexibility is a key point when writing a unit test. If you test
first, you won't incur the cost of refactoring your code for flexibility later.
7.4
Mocking an HTTP connection
To see how mock objects work in a practical example, let's use the simple application
that opens an
HTTP
connection to a remote server and reads the content of a page. In
chapter 6 we tested that application using stubs. Let's now unit test it using a mock
object approach to simulate the
HTTP
connection.
In addition, you'll learn how to write mocks for classes that don't have a Java inter-
face (namely, the
HttpURLConnection
class). We show a full scenario in which you
start with an initial testing implementation, improve the implementation as you go,
and modify the original code to make it more flexible. We also show how to test for
error conditions using mocks.
As you dive in, you'll keep improving both the test code and the sample applica-
tion, exactly as you might if you were writing the unit tests for the same application. In
the process, you'll learn how to reach a simple and elegant testing solution while mak-
ing your application code more flexible and capable of handling change.
Figure 7.2 introduces the sample
HTTP
application.
This application consists of a simple
WebClient.getContent
method performing
an
HTTP
connection to a web resource executing on a web server. We want to be able
to unit test the
getContent
method in isolation from the web resource.
Figure 7.2
The sample HTTP application before introducing the test