【问题标题】:Gtest returns SegFault when accessing variable in TEST_FGtest 在访问 TEST_F 中的变量时返回 SegFault
【发布时间】:2021-06-17 05:46:04
【问题描述】:

我是 Gtest 的初学者,在访问 TEST_F 中的类变量时遇到分段错误。以下是我的代码的 sn-p,请帮助指出这种行为背后的原因。

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
 {
 }
}

【问题讨论】:

    标签: c++ unit-testing segmentation-fault googletest


    【解决方案1】:

    您提供的代码至少存在 2 个主要问题(我没有看到 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 2011-10-26
      • 1970-01-01
      • 2016-12-15
      • 2012-07-13
      相关资源
      最近更新 更多