Java Reference
In-Depth Information
For applications that depend on a specific runtime environment, writing unit
tests is a challenge. Your tests need to be stable, and when run repeatedly, they need
to yield the same results. You need a way to control the environment in which the
tests run. One solution is to set up the real required environment as part of the tests
and run the tests from within that environment. In some cases, this approach is prac-
tical and brings real benefits (see chapter 8, which discusses in-container testing).
But it works well only if you can set up the real environment on your development
and build platforms, which isn't always feasible.
For example, if your application uses HTTP to connect to a web server provided by
another company, you usually won't have that server application available in your
development environment. Therefore, you need a way to simulate that server so you
can still write and run tests for your code.
Alternatively, suppose you're working with other developers on a project. What
if you want to test your part of the application, but the other part isn't ready? One
solution is to simulate the missing part by replacing it with a fake that behaves the
same way.
There are two strategies for providing these fake objects: stubbing and using mock
objects. Stubs, the original solution, are still very popular, mostly because they allow
you to test code without changing it to make it testable. This isn't the case with mock
objects. This chapter is dedicated to stubbing, whereas chapter 7 covers mock objects.
6.1
Introducing stubs
Stubs are a mechanism for faking the behavior of real code or code that isn't ready
yet. Stubs allow you to test a portion of a system even if the other part isn't available.
Stubs usually don't change the code you're testing but instead adapt to provide seam-
less integration.
DEFINITION A stub is a piece of code that's inserted at runtime in place of the
real code, in order to isolate the caller from the real implementation. The
intent is to replace a complex behavior with a simpler one that allows inde-
pendent testing of some part of the real code.
Here are some examples of when you might use stubs:
When you can't modify an existing system because it's too complex and fragile
For coarse-grained testing, such as integration testing between different
subsystems
Stubs usually provide high confidence in the tested system. With stubs, you aren't
modifying the objects under test, and what you are testing is the same as what will exe-
cute in production. A build or developer usually executes tests involving stubs in their
running environment, providing additional confidence.
On the downside, stubs are usually hard to write, especially when the system
to fake is complex. The stub needs to implement the same logic as the code it's
 
 
 
 
 
 
Search WWH ::




Custom Search