gpt4 book ai didi

c++ - 如何在进行 GoogleTest 时跳过源代码中的部分“代码”

转载 作者:行者123 更新时间:2023-11-30 05:30:16 24 4
gpt4 key购买 nike

我尝试在源代码中使用调试标志添加 (GOOGLE_TEST) 并将其定义在 TEST/Makefile.am 中。但事情没有奏效。我正在使用 C++ 语言。注意:我不想更改 SRC 目录代码中的任何内容,因为这会影响生产代码及其 Makefile.am

SRC 目录中的测试类

class Common: public Thread {
public:
friend class test_common;
Common {
}
~Common () {
}
virtual void ThreadMain();
protected:
virtual void ProcessData(void);
};
void Common::ProcessData(void) {
#ifndef __GOOGLE_TEST__
while (1) { }
#endif
}

测试目录中的 TESTCODE

class test_common : public ::testing::Test {
};
TEST_F(test_common, create_common) {
Common commonObj();
commonObj. ProcessData ();
}

输出

即使在 test/makefile.am 中定义了标志之后,GTest 仍然卡在 While 循环部分

最佳答案

不要依赖编译标志,在不影响生产代码的情况下使用 GMOCK 方法摆脱 while (1) 循环,代码可以像下面这样:

测试代码:

class test_common : public ::testing::Test {
};
TEST_F(test_common, create_common) {
Common commonObj();
ON_CALL(mock_if, GetBool())
.WillByDefault(Return(true));
EXPECT_CALL(mock_if, GetBool())
.Times(AtLeast(1))
.WillOnce(Return(true))
.WillOnce(Return(false));
commonObj. ProcessData ();
}

抽象代码:

class AbstractIf {
public:
AbstractIf (void) = default;
virtual ~AbstractIf (void) = default;
virtual bool GetBool() = 0;
};

模拟代码:

class MockIf : public AbstractIf {
public:
MOCK_METHOD0(GetBool,bool());
};

源代码:

class Common: public Thread {
public:
friend class test_common;
Common {
}
~Common () {
}
virtual void ThreadMain();
protected:
virtual void ProcessData(void);
AbstractIf *prov_fl_if_;
};
void Common::ProcessData(void) {
while (prov_fl_if_->GetBool()) { }
}

通过这种方式我们可以跳过我们想要的部分代码而不影响生产代码

关于c++ - 如何在进行 GoogleTest 时跳过源代码中的部分“代码”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36040870/

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