【问题标题】:Unit testing with boost::statechart使用 boost::statechart 进行单元测试
【发布时间】:2010-11-17 09:26:34
【问题描述】:

我们正在使用 boost 状态图库,并且在为代码编写单元测试时遇到了麻烦。

在我们的正常执行中,状态机从ClosedState开始:

struct BoostStateMachine : sc::state_machine<BoostStateMachine, ClosedState >

我们想测试一个特定的状态转换,而不必遍历状态机直到那个状态,例如我们想在AnotherState 开始测试。问题是sc::state_machine 在其初始状态下被模板化。向状态机提供导致测试状态的所有事件通常需要大量工作并使测试复杂化。

一个原始的解决方案是编写特殊的仅调试事件并将其添加到ClosedState。此事件将触发立即转换到 AnotherState

你知道完成任务的其他方法吗?

【问题讨论】:

    标签: c++ unit-testing boost boost-statechart


    【解决方案1】:

    我承认这不是很好,但是

    #ifdef DEBUG
    typedef AnotherState StartingState;
    #else
    typedef ClosedState StartingState;
    #endif
    struct BoostStateMachine : sc::state_machine<BoostStateMachine, StartingState > {...
    

    编辑地址注释

    #ifndef INITIAL_STATE
    #define INITIAL_STATE ClosedState
    #endif
    struct BoostStateMachine : sc::state_machine<BoostStateMachine, INITIAL_STATE > {...
    

    当然这意味着您需要重新编译才能进行每个测试 =[

    我们可以尝试以下方法:

    typedef<class InitialState>
    struct StateMachine : sc::state_machine< typename /*?*/ StateMachine<InitialState>, InitialState > {...}
    
    typedef StateMachine<ClosedState> BoostStateMachine; //default case
    
    #ifdef DO_TESTS
        ...
        StateMachine<AnotherState> astate1;
        ...
        StateMachine<AnotherState2> astate2;
        ...
        StateMachine<AnotherState3> astate3;
        ...
    #endif
    

    当它是一个需要以不同状态开始的子状态时,这当然没有帮助。但同样的事情也适用:

    typedef <typename InitialChild>
    struct ClosedState : sc::simple_state< ClosedState<InitialChild>, BoostStateMachine, InitialChild > {...};
    

    或类似的东西。我以前做过模板化状态(这样我就可以有共同的子状态序列),它是一个皇家 PITA 来调试(更多的是状态图的其余部分)。

    【讨论】:

    • 行不通,因为我们自然需要许多以不同状态开始的测试用例。
    • @FireAphis 在我原来的帖子中看到编辑以另一种方式另一种方式
    • 感谢您详细的回答。我想,从技术上讲,我真的不需要 DO_TESTS ifdef,因为这些类型无论如何都不会在生产代码中使用。对吗?
    • @FireAphis 由于 Boost.Statechart 使用编译时元编程来完成很多它的魔力,您应该包含 ifdef DO_TESTS 以便您的编译器不会浪费时间来实例化这些测试类型。确实,一个不错的优化器会从运行时完全消除测试代码,但是如果您不删除测试,您的编译时间可能/将会更大。
    猜你喜欢
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多