如何对状态机进行单元测试?
假设我有一个 Order 类,它可以处于三种不同的状态:CheckedState、PaidState 和 OrderedState。
状态机将使用标准状态设计模式(Gof)来实现。
您通常如何对此进行单元测试?您是否为每个状态类(CheckStateFixture
、PaidFixture
,...)使用一个固定装置,并为上下文类使用另一个固定装置(OrderFixture
)?或者您是否只使用一个用于放置所有单元测试的上下文类 (Order
) 固定装置?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我更喜欢将国家基础设施与实体本身分开。
因此,您将拥有
对于状态基础设施,我建议每个实体使用单个固定装置,因此订单状态基础设施的一个
OrderStateFixture
就足够了。主要测试是确保订单状态正确切换的测试:
Order.Paid(amount)
方法 Order.State 切换到 Paid 后Order.Verify()
无例外地返回 true/pass - Order.State 变为 Checked/VerifiedI preffer to keep State Infrastructure separately from entity itself.
So you would have
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:
Order.Paid(amount)
method Order.State switches to PaidOrder.Verify()
returns true/pass without exception - Order.State becomes Checked/Verified