Unit Tests
A unit test relies on assertions to verify the behavior of code. An assertion
throws an error if an expectation isn’t met, such as when a field doesn’t match
an expected value. A unit test succeeds if it completes
without falling any
assertions or throwing any exceptions. Java provides the assert keyword,
but it relies on JVM arguments to enable and it’s preferable to use a framework
with more flexibility. JUnit is a popular unit testing
framework that includes
a rich API for assertions as well as support for test fixtures.
Test Fixtures
A test fixture is a fixed state of objects used as a baseline for running tests.
For example, a test fixture could drop and recreate an in-memory database
to allow data access tests to work on a clean
set of data after every
test execution.
Mock Objects
Mock objects mimic the behavior of objects that are too impractical
to incorporate into unit tests. For example, it would
be prohibitive to charge
a credit card or launch a missile every time a unit test runs. Mock objects
implement the same interface as the objects they mimic,
allowing developers
to simulate controlled scenarios without modifying the code that’s being tested.
Mock objects can be created manually, but frameworks such as Mockito provide
powerful proxies that can trace and verify the behavior of method calls.