Java Reference
In-Depth Information
Why you need automated unit tests
Automated unit testing is the easiest way we know to prevent regressions and to
test those code nooks and crannies that are often overlooked during manual inte-
gration testing. As an added bonus, having code built on a solid foundation of
unit tests can give you the confidence to explore design improvements, refactor-
ings, new features, and other changes that you might otherwise deem too risky to
pursue. If you can trust your unit tests, recertifying your code is as simple as
rerunning your tests.
When to write unit tests
Everyone has their own opinion on testing, but most developers share a basic
tenet: the earlier the better. Members of the Extreme Programming camp insist
on having you write your tests first, before you begin coding the classes they're
being designed to test. This approach has several advantages, such as giving you
an idea of the type of operations that are required of the code and assuring the
testability of your class. Tests are easy to write, but if you don't get in the habit of
writing unit tests as you go, it's easy to fall behind. A common suggestion you'll
hear is “Code a little, test a little.”
Another good practice is to create a new unit test for each bug that is reported.
Design the test to exploit the bug and reproduce its behavior. The unit test will of
course fail until the bug is resolved, making it easy to know when you've fixed it.
Just code until the test passes! This also ensures that the bug will never bite you
again, as long as you continue running your unit tests.
When to run unit tests
You should run your unit tests frequently to stop bugs from creeping into your
code. Ideally, every developer should run the full set of unit tests before each
check-in (refer to chapter 8 for information on version control), to ensure that
none of their changes have broken any of the existing code. You should also con-
sider running unit tests on a nightly basis, perhaps as part of a nightly build pro-
cess. Java build tools such as Ant fully integrate with JU nit, allowing you to easily
automate not only the running of tests but the reporting of the results as well.
7.1.2
Exploring the JUnit API
JU nit tests are collections of methods designed to exercise all the possible opera-
tions your code is expected to perform. These testing methods are included in a
Java class that is passed to a JU nit-aware application, which can then put them
through their paces and report the results. A test case is a class that contains the
testing code.
 
 
 
 
 
 
 
 
 
 
 
Search WWH ::




Custom Search