Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test a state machine?

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?

like image 212
Riana Avatar asked Oct 17 '11 18:10

Riana


Video Answer


1 Answers

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
like image 108
sll Avatar answered Sep 22 '22 17:09

sll