A stub is a component that doesn't actually do anything other than declare itself and the parameters it accepts.
Encapsulated software (components, subsystems, classes, etc) can be is tested by sending inputs to its
interface, waiting for the software to process them, then checking the results. In the course of its processing, a
sotware component very likely uses other components by sending inputs to them and using their results:
Fig1: Testing a Component you've implemented
The components you use may cause problems for your testing. They:
-
May not be implemented yet.
-
May have defects that prevent your tests from working or make you spend a lot of time discovering that a test
failure was not caused by your component.
-
May make it hard to run tests when you need to. For instance, if a component is a commercial database, your company
might not have enough floating licenses for everyone. Or one of the components may be hardware that's available
only at scheduled times in a separate lab.
-
May make testing so slow that tests aren't run often enough. For example, initializing the database might take five
minutes per test.
-
May be difficult to provoke into produciong certain results. For example, you may want each of your methods that
writes to disk to handle "disk full" errors. How do you make sure the disk fills at just the moment that method is
called?
To avoid these problems, you may choose to use stub components (also called mock objects). Stub
components behave like the real components, at least for the values that your component sends them while responding to
its tests. They may go beyond that: they may be general-purpose emulators that seek to faithfully mimic most or
all the component's behaviors. For example, it's often a good strategy to build software emulators for hardware. They
behave just like the hardware, only slower. They're useful because they support better debugging, more copies of them
are available, and they can be used before the hardware is finished.
Fig2: Testing a Component you've implemented by stubbing out a dependent
component
Stubs have two disadvantages.
-
Stubs can be expensive to build - this is especially true for emulators.
-
Stubs need to be maintained since they're also software.
-
Stubs may mask errors. For example, suppose your component uses trigonometric functions, but no math library is
available yet. You could construct a stub for sine that returns preset values for specific inputs. All is fine
until you integrate your component with the real trigonometric library, and you discover that the sine function
takes arguments in radians and the expected results are now different from what the test expects. The
good news is that a code defect was found - your code needs to use radians. The bad news is that the error was
discovered later in the development cycle than desireable.
For further information related to stubs, see the following:
|