Java Reference
In-Depth Information
Figure 7.3
The steps involved in a test using mock objects
7.4.1
Defining the mock objects
Figure 7.3 illustrates the definition of a mock object. The
MockURL
class stands in for
the real
URL
class, and all calls to the
URL
class in
getContent
are directed to the
Mock-
URL
class. As you can see, the test is the controller: it creates and configures the behav-
ior the mock must have for this test; it (somehow) replaces the real
URL
class with the
MockURL
class; and it runs the test.
Figure 7.3 shows an interesting aspect of the mock objects strategy: the need to be
able to swap the mock into the production code. The perceptive reader will have
noticed that because the
URL
class is final, it's not possible to create a
MockURL
class
that extends it.
In the coming sections, we demonstrate how to perform this feat in a different way
(by mocking at another level). In any case, when using the mock objects strategy,
swapping in the mock instead of the real class is the hard part. This may be viewed as a
negative point for mock objects, because we usually need to modify our code to pro-
vide a trapdoor. Ironically, modifying code to encourage flexibility is one of the stron-
gest advantages of using mocks, as explained in section 7.3.1.
7.4.2
Testing a sample method
The example in listing 7.6 demonstrates a code snippet that opens an
HTTP
con-
nection to a given
URL
and reads the content found at that
URL
. Let's imagine that
it's one method of a bigger application that we want to unit test, and let's unit test
that method.