Java Reference
In-Depth Information
8.4
Comparing stubs, mock objects, and in-container
testing
In this section we compare 2 the different approaches we presented to test compo-
nents. This section draws from the many questions in forums and mailing lists asking
about the pros and cons of stubs, mock objects, and in-container testing.
8.4.1
Stubs pros and cons
We introduced stubs as our first out-of-container testing technique in chapter 6. Stubs
work well to isolate a given class for testing and asserting the state of its instances. For
example, stubbing a servlet container allows us to track how many requests were
made, what the state of the server is, or what URL s where requested.
Using mocks, however, we can test the state of the server and its behavior. When
using mock objects, we code and verify expectations; we check at every step to see
whether tests execute domain methods and how many times tests call these methods.
One of the biggest advantages of stubs over mocks is that stubs are easier to under-
stand. Stubs isolate a class with little extra code compared to mock objects, which
require an entire framework to function. The drawback of stubs is that they rely on
external tools and hacks, and they don't track the state objects they fake.
Going back to chapter 6, we easily faked a servlet container with stubs; doing so
with mock objects would be much harder because we'd need to fake container objects
with state and behavior. Here's a summary of stubs pros and cons.
Pros:
They're fast and lightweight.
They're easy to write and understand.
They're powerful.
Tests are coarser grained.
Cons:
Specialized methods are required to verify state.
They don't test the behavior of faked objects.
They're time consuming for complicated interactions.
They require more maintenance when the code changes.
8.4.2
Mock objects pros and cons
The biggest advantage of mock objects 3 over in-container testing is that mocks
don't require a running container in order to execute tests. Tests can be set up
quickly and run quickly. The main drawback is that the tested components don't
2
For an in-depth comparison of the stubs and mocks technology, see ”Mocks Aren't Stubs” by Martin Fowler:
http://martinfowler.com/articles/mocksArentStubs.html.
3
For an in-depth comparison of the mocks and in-container testing, see “Mock Objects vs. In-Container Test-
ing”: http://jakarta.apache.org/cactus/mock_vs_cactus.html.
 
 
 
 
 
 
Search WWH ::




Custom Search