How to unit test a state machine?

7.9k Views Asked by At

Suppose I have an Order class, which can be in three different states : CheckedState, PaidState and OrderedState.

The state machine will be implemented using the standard State Design Pattern (Gof).

How do you usually unit test this? Do you use a fixture for each state class (CheckStateFixture, PaidFixture, ...) and one another (OrderFixture) for the context class? Or do you use only one fixture for the context class (Order) in which you'll put all the unit tests?

1

There are 1 best solutions below

2
On BEST ANSWER

I preffer to keep State Infrastructure separately from entity itself. So you would have

  • Entity class (Order)
  • State infrastructure classes

For States Infrastructure I would suggest using single fixture per entity, so one OrderStateFixture for Order States Infrastructure will be enough.

The main tests would be the tests which ensures that Order state switches correctly:

  • Ensure that initial state of an order is NotChecked
  • After the successfull execution of the Order.Paid(amount) method Order.State switches to Paid
  • If Order.Verify() returns true/pass without exception - Order.State becomes Checked/Verified