简体   繁体   English

单元测试大型非成员函数

[英]Unit testing large non-member functions

I have a function, which I'd like to get under test. 我有一个要测试的功能。 However, it's very large and creates a finite state machine. 但是,它非常大,并创建了一个有限状态机。 The function looks roughly like: 该函数大致如下:

std::auto_ptr<IFiniteStateMachine> CreateFSM() 
{
    std::auto_ptr<IFiniteStateMachine> = apFSM( new CFiniteStateMachine() );

    std::list<IState*> listStates;

    listState.push_back( new CStateFoo( /*params*/ ) );
    listState.push_back( new CStateBar( /*params*/ ) );

    // etc.

    apFSM->AddState( listStates );

    // Define the transition table
    // 1st param: event received
    // 2nd param: current state
    // 3rd param: next state
    apFSM->AddTransition( "EventA", "StateFoo", "StateBar" );

    // etc.

    return apFSM;
}

Basically, this function just creates a FSM, states, and transition tables. 基本上,此功能仅创建FSM,状态和转换表。 Each of the individual components (the IFiniteStateMachine and IState classes) are testable. 每个单独的组件(IFiniteStateMachine和IState类)都是可测试的。

So my question is: can a function like this be put under test? 所以我的问题是:可以对这样的函数进行测试吗? I'm not sure how you would even verify that this function worked as expected. 我不确定您如何验证此功能是否按预期工作。 I could probably divide it up into smaller functions that create states and transitions. 我可能可以将其分为创建状态和转换的较小函数。 However, a function that just created these states also seems rather complicated and hard to test. 但是,刚刚创建这些状态的函数似乎也相当复杂且难以测试。

Thanks. 谢谢。

Ask yourself what should be true after the function has run? 问问自己,函数运行后该怎么做? Sounds like in this case a certain state machine should be in place - so that's what you should check for so you can do something like: 听起来在这种情况下,应该有某种状态机-这就是您应该检查的内容,因此您可以执行以下操作:

FSM expectedFSM = Factory.blankFSM().addState().addTransition().... etc
FSM actualFSM = CreateFSM();
ASSERT(expectedFSM == actualFSM); //assuming such == exists

or sometimes an easier way of doing this could be using string represntation/serialization: 或者有时更简单的方法可以使用字符串表示/序列化:

String expectedFSMStr = loadFSMFromFile(expectedOutput1);
FSM actualFSM = CreateFSM();
ASSERT_EQUALS(expectedFSMStr, actualFSM.toString());

This can be easier to debug and is very useful if your classes have a reliable toStrinb/serialization method. 如果您的类具有可靠的toStrinb / serialization方法,则这将更易于调试,并且非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM