Java Reference
In-Depth Information
@After
public void
tearDown() {
verify(mockHttpServletRequest);
verify(mockHttpSession);
}
}
We start by importing the necessary classes and methods using Java 5 static imports
B
.
We use the
EasyMock
class extensively, which has similar syntax to the
JU
nit Hamcrest
matchers. Next, we declare instance variables for the objects
C
we want to mock,
HttpServletRequest
and
HttpSession
. The
setUp
method annotated with
@Before
D
runs before each call to
@Test
methods; this is where we instantiate all of our mock
objects. Next, we implement our tests following this pattern:
1
Set our expectations using the EasyMock
API
E
.
2
Invoke the
replay
method to finish declaring our expectations
F
.
3
Assert test conditions on the servlet
G
.
Finally, at
H
the
@After
method (executed after each
@Test
method) calls the Easy-
Mock
verify
API
I
to check whether the mocked objects met all of our pro-
grammed expectations.
Mocking a minimal portion of a container is a valid approach to testing compo-
nents. But mocking can be complicated and require a lot of code. As with other kinds
of tests, when the servlet changes, the test expectations must change to match. Next,
we look at easing this task.
H
I
8.3
In-container testing
Another approach to testing the
SampleServlet
is to run the test cases where the
HttpsServletRequest
and
HttpSession
objects live, in the container itself. This
avoids the need to mock any objects; we access the objects and methods we need in
the real container.
For our example, we need
HttpServletRequest
and
HttpSession
to be real
objects managed by the container. Using a mechanism to deploy and execute our tests
in a container, we have in-container testing. Next, we see what options are available to
implement in-container tests.
8.3.1
Implementation strategies
We have two architectural choices to drive in-container tests: server-side and client-
side. As we stated previously, we can drive the tests directly by controlling the server-
side container and the unit tests. Alternatively, we can drive the tests from the client
side, as shown in figure 8.1.
Once the tests are packaged and deployed in the container and to the client, the
JU
nit test runner executes the test classes on the client (1). A test class opens a con-
nection via a protocol like
HTTP
(S) and calls the same test case on the server side (2).
The server-side test case operates on server-side objects, which are normally available
(such as
HttpServletRequest
,
HttpServletResponse
,
HttpSession
,
BundleContext
,