Java Reference
In-Depth Information
If you want to thoroughly test your application, including how runtime objects
interact with each other, you need to use black box integration tests as well as white
box tests.
We've completed our overview of code coverage and Cobertura to see precisely
which parts of an application unit tests exercise. Let's now move on to how different
implementation techniques affect how to write tests for an application.
5.2
Writing testable code
This chapter is dedicated to best practices in software testing. We introduced JU nit (in
chapters 1, 2, and 3) and discussed different types of tests (in chapter 4). We're now
ready to get to the next level: writing code that's easy to test. Sometimes writing a sin-
gle test case is easy, and sometimes it isn't. It all depends on the level of complexity of
the application. A best practice avoids complexity as much as possible; code should be
readable and testable. In this section, we discuss some best practices to improve your
architecture and code. Remember that it's always easier to write easily testable code
than it is to refactor existing code to make it easily testable.
5.2.1
Public APIs are contracts
One of the principles in providing backward-compatible software states says that you
“never change the signature of a public method.” An application code review will
show that most calls are made to public API s. If you change the signature of a public
method, then you need to change every call site in the application and unit tests.
Even with refactoring wizards in tools like Eclipse, you must always perform this task
with care.
In the open source world, and for any API made public by a commercial product,
life can get even more complicated—many people use your code, and you should be
careful of the changes you make to stay backward compatible.
Public methods become the articulation points of an application among compo-
nents, open source projects, and commercial products that usually don't even know of
one another's existence.
Imagine a public method that takes a distance as a double parameter and a black
box test to verify a computation. At some point, the meaning of the parameter changes
from miles to kilometers . Your code still compiles, but the runtime breaks. Without a unit
test to fail and tell you what's wrong, you may spend a lot of time debugging and talk-
ing to angry customers. This example illustrates that you must test all public methods.
For nonpublic methods, you need to go to a deeper level and use white box tests.
5.2.2
Reduce dependencies
Remember that unit tests verify your code in isolation. Your unit tests should instanti-
ate the class you want to test, use it, and assert its correctness. Your test cases should be
simple. What happens when your class instantiates, directly or indirectly, a new set of
objects? Your class now depends on these classes. In order to write testable code, you
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search