Expert Spring MVC and Web Flow

(Dana P.) #1
The basic definition of a unit testis “a discrete test condition to check correctness of an
isolated software module.” Although we believe that this statement is correct, there is perhaps
a better way to define a unit test. We argue that a test should strive to follow these tenets if it is
trulyto be called a unit test:


  • Run fast: A unit test must run extremely fast. If it needs to wait for database connec-
    tions or external server processes, or to parse large files, its usefulness will quickly
    become limited. A test should provide an immediate response and instant gratification.

  • Zero external configuration: A unit test must not require any external configuration
    files—not even simple text files. The test’s configurations must be provided and set by
    the test framework itself by calling code. The intent is to minimize both the runtime of
    the test and to eliminate external dependencies (which can change over time, becom-
    ing out of sync with the test). Test case conditions should be expressed in the test
    framework, creating more readable test conditions.

  • Run independent of other tests: A unit test must be able to run in complete isolation. In
    other words, the unit test can’t depend on some other test running before or after itself.
    Each test is a stand-alone unit.

  • Zero external resources: A unit test must not depend on any outside resources, such as
    database connections or web services. Not only will these resources slow the test down,
    but they are outside the control of the test and thus aren’t guaranteed to be in a correct
    state for testing.

  • Leave external state untouched: A unit test must not leave any evidence that it ever ran.
    Unit tests are written to be repeatable, so they must clean up after themselves. Obvi-
    ously, this is much easier when the test doesn’t rely on external resources (which are
    often harder to clean up or restore).

  • Test smallest unit of code: A unit test must test the smallest unit of code possible in
    order to isolate the code under test. In object-oriented programming, this unit is usu-
    ally a method of an object or class. Writing unit tests such that a method is tested
    independently of other methods reduces the number of code lines that could contain
    the potential bug.


■CautionObviously, Spring applications rely heavily upon the ApplicationContextand its XML config-
uration files at runtime. Your unit tests, however, should not rely on these facilities. Many if not all of Spring’s
practices promote the ability to run your code outside of Spring itself. Your code should always be able to be
unit tested without the ApplicationContext’s involvement. To test the wiring and configuration of your
system, see “Integration Tests” later in this chapter.

284 CHAPTER 10 ■TESTING SPRING MVC APPLICATIONS

Free download pdf