我是Gtest的初学者,在访问TEST_F中的类变量时面临分段错误。下面是我的代码片段,请帮助指出这种行为背后的原因。
main.cpp
#include <Foo.h>
#include "gtest/gtest.h"
int main(int argc, char* argv[])
{
InitalRegister();
::testing::InitGoogleTest(&argc, argv);
int rc = RUN_ALL_TESTS();
return rc;
}
Foo.h
void InitalRegister();
class TestFoo // Required for registration
{
//Do nothing
};
Foo.cpp
#include "gtest/gtest.h"
#include <Foo.h>
#include <Bar.h>
void InitalRegister()
{
//Doing few registration
}
Bar* newBar;
void Bar_called_init(void *inValue) // will be called as part of InitialRegsiter and inValue will be holding a valid value
{
newBar = (Bar)*inValue;
}
class UnitTestFoo : public::testing::Test
{
public:
Bar* inValue;
Bar* GetValue();
protected:
virtual void SetUp() override
{
inValue = GetValue();//able to access inValue here
}
};
Bar* UnitTestFoo::GetValue()
{
inValue = newBar;
}
TEST_F(UnitTestFoo, Foo1)
{
if (inValue != NULL) // Getting segfault when accessing inValue here
{
}
}
您提供的代码至少有两个主要问题(我看不到Bar.h
(:
-
GetValue
不返回任何值,而它应该返回Bar*
,请将您的代码更新为Bar* UnitTestFoo::GetValue() { inValue = newBar; return inValue; }
-
Bar_called_init
试图取消引用void*
指针,这将导致编译错误,请将您的代码更新为类似的内容void Bar_called_init(void *inValue) { newBar = (Bar*)inValue; }
您在机器上进行代码编译吗?通过这两个修复,我能够看到测试通过:
[ RUN ] UnitTestFoo.Foo1
[ OK ] UnitTestFoo.Foo1 (0 ms)