【问题标题】:Why is Google Test segfaulting?为什么 Google 测试会出现段错误?
【发布时间】:2014-05-19 20:24:21
【问题描述】:

我是 Google Test 的新手,我正在使用提供的示例。我的问题是,当我引入失败并设置GTEST_BREAK_ON_FAILURE=1(或使用命令行选项)时,GTest 将出现段错误。

我正在考虑this example。如果我在任何测试中插入这样的东西,我将开始得到段错误:

EXPECT_EQ(8, 2*3);

重申一下,只有当我还设置了GTEST_BREAK_ON_FAILURE=1 时。我已经从命令行运行,也使用 gdb 运行。如果没有设置该环境变量,它会报告错误但不会出现段错误。

任何可能导致此/我做错了什么的线索?我一直在寻找类似的问题,但我还没有遇到任何问题。

仅供参考,我使用的是在 64 位 CrunchBang Linux 11“Waldorf”上运行的 Google 测试版本 1.7.0。

编辑代码示例:

// Tests factorial of positive numbers.
TEST(FactorialTest, Positive) {
  EXPECT_EQ(1, Factorial(1));
  EXPECT_EQ(2, Factorial(2));
  EXPECT_EQ(6, Factorial(3));
  EXPECT_EQ(40320, Factorial(8));
}

调试器输出:

(gdb) run
Starting program: /home/yourfavoriteprotein/bin/cpp_unit_test_frameworks/gtest-1.7.0/samples/mytest 
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Running main() from test_main.cc
[==========] Running 6 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 3 tests from FactorialTest
[ RUN      ] FactorialTest.Negative
[       OK ] FactorialTest.Negative (0 ms)
[ RUN      ] FactorialTest.Zero
[       OK ] FactorialTest.Zero (0 ms)
[ RUN      ] FactorialTest.Positive
sample1_unittest.cc:112: Failure
Value of: 2*3
  Actual: 6
Expected: 8

Program received signal SIGSEGV, Segmentation fault.
0x0000000000413427 in testing::UnitTest::AddTestPartResult(testing::TestPartResult::Type,         char const*, int, std::string const&, std::string const&) ()
(gdb) quit

【问题讨论】:

    标签: c++ unit-testing debugging googletest


    【解决方案1】:

    GTEST_BREAK_ON_FAILURE=1 表示如果测试失败,Google 测试 drops you into the debugger

    碰巧,一种简单、可移植的方式让您进入调试器是触发段错误。

    换句话说,这种行为是设计使然; Google Test 故意触发段错误以使调试器运行。 (请参阅 Google 测试代码中的 here。)

    【讨论】:

    • 嗯,好的。你能告诉我进入调试器的步骤吗?我已经尝试在 gdb 中运行测试,但听起来这不是正确的用法?
    • 使用此选项集在 gdb 中运行它应该是正确的;它应该导致执行在违规行停止。然后你可以使用普通的 GDB 命令来调查。这不工作吗?
    • 不,它会在 gdb 中出现段错误,除非这是设计使然:(我会将输出添加到我的问题中)
    • @yourfavoriteprotein 是的,这是设计使然。它不会通过启动调试器来“让你进入调试器”。它只是停止程序(通过段错误),所以如果您在调试器中运行测试,您可以检查堆栈跟踪并在它失败的地方进行基本调试。
    • 好的,非常感谢。说得通。那我必须把它标记为已回答。
    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 2013-01-29
    • 2013-02-11
    相关资源
    最近更新 更多