【问题标题】:How to unit test a state machine?如何对状态机进行单元测试?
【发布时间】:2011-10-17 18:17:27
【问题描述】:

假设我有一个Order 类,它可以处于三种不同的状态:CheckedStatePaidStateOrderedState

状态机将使用标准状态设计模式 (Gof) 实现。

您通常如何对此进行单元测试?您是否为每个状态类(CheckStateFixturePaidFixture、...)和上下文类使用另一个(OrderFixture)?或者您是否只使用一个夹具作为上下文类 (Order),您将在其中放置所有单元测试?

【问题讨论】:

    标签: unit-testing design-patterns state-pattern


    【解决方案1】:

    我更喜欢将 State Infrastructure 与实体本身分开。 所以你会有

    • 实体类(订单)
    • 状态基础设施类

    对于States Infrastructure,我建议每个实体使用一个fixture,因此一个OrderStateFixture 用于Order States Infrastructure 就足够了。

    主要测试是确保订单状态正确切换的测试:

    • 确保订单的初始状态为 NotChecked
    • Order.Paid(amount) 方法成功执行后,Order.State 切换到 Paid
    • 如果 Order.Verify() 返回 true/无异常通过 - Order.State 变为 Checked/Verified

    【讨论】:

    • 感谢您的回答!不过,我想澄清一下,您会将这些转换测试放在 OrderFixture 或 OrderStateFixture 中吗?
    • 这取决于谁负责进行转换,如果 Order 自己进行转换 - 这将是 OrderFixture 或 OrderStateFixture
    猜你喜欢
    • 2017-12-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多