gpt4 book ai didi

c++ - 通过重复的操作序列简化 GTest 用例

转载 作者:行者123 更新时间:2023-11-28 06:37:55 25 4
gpt4 key购买 nike

我需要测试 MyController 是否使用不同的值重复调用一系列操作。下面是相关的代码,如何简化重复 block 调用不同值的相同操作?

class MyControllerTest : public ::testing::Test
{
protected:
MyControllerTest() :
m_mycontroller(m_dataBroker, m_eventBroker)
{
}

testing::MockDataBroker m_dataBroker;
testing::MockEventBroker m_eventBroker;
MyController m_mycontroller;
};


TEST_F(MyControllerTest, ConfigureSequence)
{

{
InSequence dummy;
EXPECT_CALL(m_dataBroker, Prepare());
EXPECT_CALL(m_dataBroker, SetItem(Data::ID, SP::ITEM_1));
EXPECT_CALL(m_dataBroker, End());
EXPECT_CALL(m_eventBroker, DispatchEvent(Events::ADD, _));
m_mycontroller.Event(Events::ADDED);

EXPECT_CALL(m_dataBroker, Prepare());
EXPECT_CALL(m_dataBroker, SetItem(Data::ID, SP::ITEM_2));
EXPECT_CALL(m_dataBroker, End());
EXPECT_CALL(m_eventBroker, DispatchEvent(Events::ADD, _));
m_mycontroller.Event(Events::ADDED);

EXPECT_CALL(m_dataBroker, Prepare());
EXPECT_CALL(m_dataBroker, SetItem(Data::ID, Event::SP::ITEM_3));
EXPECT_CALL(m_dataBroker, End());
EXPECT_CALL(m_eventBroker, DispatchEvent(Events::ADD, _));
m_mycontroller.Event(Events::ADDED);

EXPECT_CALL(m_dataBroker, Prepare());
EXPECT_CALL(m_dataBroker, SetItem(Data::ID, Event::SP::ITEM_4));
EXPECT_CALL(m_dataBroker, End());
EXPECT_CALL(m_eventBroker, DispatchEvent(Events::ADD, _));
m_mycontroller.Event(Events::ADDED);

EXPECT_CALL(m_dataBroker, Prepare());
EXPECT_CALL(m_dataBroker, SetItem(Data::ID, Event::SP::ITEM_5));
EXPECT_CALL(m_dataBroker, End());
EXPECT_CALL(m_eventBroker, DispatchEvent(Events::ADD, _));
m_mycontroller.Event(Events::ADDED);

m_mycontroller.start();
}

}

最佳答案

for 循环就足够了

const vector<...> items = {Event::SP::ITEM_1, Event::SP::ITEM_2, ...};
for (const auto& item : items) {
EXPECT_CALL(m_dataBroker, Prepare());
EXPECT_CALL(m_dataBroker, SetItem(Data::ID, SP::ITEM_1));
EXPECT_CALL(m_dataBroker, End());
EXPECT_CALL(m_eventBroker, DispatchEvent(Events::ADD, _));
m_mycontroller.Event(Events::ADDED);
}
m_mycontroller.start();

EXPECT_CALL 宏没有什么特别之处。它们的底层只是对模拟对象 m_dataBroker 的简单函数调用。

关于c++ - 通过重复的操作序列简化 GTest 用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26489674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com