State transition: what can and cannot happen

level 1 · 20 min · state transition testing

Some systems have memory: what happens depends on the state they are in. An order is created, paid, shipped and delivered, and can be cancelled at certain moments. The same action, “cancel”, is valid in one state and forbidden in another.

A state transition diagram draws the states as boxes and the allowed changes as arrows. Each arrow becomes a test. But bugs also hide in what should be refused: that is why every state needs at least one forbidden-change test.

Rule of thumb. Test each allowed transition and, from each state, at least one forbidden transition, which must be refused.

Explore the rule

The store tracks the order with nextStatus(status, event). Choose an event and see what happens from the current state.

Current state: created

Choose an event.
Allowed state changes
FromEventTo
createdpaypaid
createdcancelcancelled
paidshipshipped
paidcancelcancelled
shippeddeliverdelivered

Any other combination is refused.

Exercise: write the tests

Your tests must pass on the correct code and fail on the 4 planted bugs.

nextStatus(status, event) moves an order from one state to the next. The contract lists the allowed moves; every other combination is an error.

Write tests for the allowed transitions and for forbidden ones. A bug that allows a move it should refuse stays hidden unless a test tries exactly that move.

/**
 * Next status of an order after an event.
 * Allowed moves:
 * - created + "pay" gives "paid".
 * - created + "cancel" gives "cancelled".
 * - paid + "ship" gives "shipped".
 * - paid + "cancel" gives "cancelled".
 * - shipped + "deliver" gives "delivered".
 * Any other combination throws Error("Invalid transition").
 * @param {string} status  "created", "paid", "shipped", "delivered" or "cancelled".
 * @param {string} event   "pay", "ship", "deliver" or "cancel".
 * @returns {string}
 */
function nextStatus(status, event)

Coverage radar: ranges and limits your tests already touch

Allowed changes

  • created + pay → paid: covered
  • created + cancel → cancelled: not yet
  • paid + ship → shipped: not yet
  • paid + cancel → cancelled: not yet
  • shipped + deliver → delivered: not yet

One forbidden change from each state

  • created: not yet
  • paid: not yet
  • shipped: not yet
  • delivered: not yet

Your tests

0 of 4 bugs detected

  • Bug 1: hidden
  • Bug 2: hidden
  • Bug 3: hidden
  • Bug 4: hidden

References

  • ISTQB® Certified Tester Foundation Level v4.0, section 4.2.4, State Transition Testing. © ISTQB®.