Choose a test level by risk

Unit, integration, and API tests answer different questions. One scenario may need several levels because an isolated rule, component interaction, and external HTTP contract have different failure points.

LevelWhat it checksRefund example
UnitAn isolated rule or calculationA refund is forbidden after 14 days
IntegrationComponent interaction and storageA repeated request does not create a duplicate
APIThe external HTTP contractA negative amount returns status 400

Unit test: a fast signal for a rule

For example, RefundPolicy can receive a number of days and whether a previous refund exists, then determine whether the operation is allowed.

  • Suitable for business rules, validators, and calculations.
  • Does not require a database, network, or full HTTP context.
  • Quickly localizes an error and is convenient for TDD.
  • Does not prove transaction, serialization, or repository behavior.
  • Does not replace an integration test when the risk lies at a component boundary.

Integration test: checking interaction

An integration test is appropriate when the real repository, database constraints, transactions, data mapping, or service interaction matter. For a refund, it can confirm that a repeated request does not create a second record.

The signal is stronger but more expensive: the test environment takes longer to start. Use a narrow test slice, Testcontainers, or existing project profiles instead of starting the entire application without need.

An API test protects the client contract

What to checkExample
Route and methodPOST to the refund endpoint
Status400 for a negative amount
JSON bodyThe agreed error code and message
Validation and headersThe response before calling dangerous logic
AuthorizationCorrect behavior for a role without access

How to delegate test generation

  1. Ask Claude to read neighboring tests.
  2. Name the risk and required verification level.
  3. Specify the package or file.
  4. Forbid changes to production code, helpers, and dependencies without approval.
  5. Ask it to follow the existing style.
  6. Review assertions and the diff after generation.

Canonical lesson source · JavaRush

Open JavaRush material