如何使用 Google 测试捕获分段错误?

How to catch segmentation fault with Google Test?

如何测试函数不会产生分段错误?

这是我现在知道的,我可以做的:

EXPECT_DEATH(foo(nullParameter))

在函数旁边,产生了一个分段错误,这是我想让它失败的行为。上面的代码片段将使测试通过,因为这是预期的,进程的死亡。

现在,我怎样才能让它失败?

崩溃的测试已经失败(大概您不希望 任何 代码出现段错误)。与任何其他测试一样,只需测试您期望的行为。

这是一个函数,如果传递了一个空指针参数,就会出现段错误,否则 不是:

int deref(int * pint)
{
    return *pint;
}

这是一个测试该行为的 googletest 程序:

main.cpp

#include <gtest/gtest.h>

int deref(int * pint)
{
    return *pint;
}


TEST(test_deref_1,will_segfault)
{
    ASSERT_EXIT((deref(nullptr),exit(0)),::testing::KilledBySignal(SIGSEGV),".*");
}


TEST(test_dref_2,will_not_segfault)
{
    int i = 42;
    ASSERT_EXIT((deref(&i),exit(0)),::testing::ExitedWithCode(0),".*");
}


int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

编译并link:

$ g++ -Wall -Wextra -pedantic -o tester main.cpp -pthread -lgtest

运行:

$ ./tester 
[==========] Running 2 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 1 test from test_deref_1
[ RUN      ] test_deref_1.will_segfault
[       OK ] test_deref_1.will_segfault (168 ms)
[----------] 1 test from test_deref_1 (168 ms total)

[----------] 1 test from test_dref_2
[ RUN      ] test_dref_2.will_not_segfault
[       OK ] test_dref_2.will_not_segfault (1 ms)
[----------] 1 test from test_dref_2 (1 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 2 test cases ran. (169 ms total)
[  PASSED  ] 2 tests.

据我所知,TEST(test_deref_1,will_segfault)是一个毫无意义的测试, 因为我想不出任何情况下我想保证 我自己认为程序会由于对 我写的功能。

TEST(test_dref_2,will_not_segfault) 可能是一种有用的测试。有效, 这是一个测试程序:

int main()
{
    int i = 42;
    defref(&i);
    exit(0);
}

将由 exit(0) 而不是以任何过早的异常方式终止。一个更好的名字 该测试可能是 TEST(test_dref,does_not_crash) 或类似的。

它可能是一种有用的测试,因为它可能存在很大的风险 失败,如果defref是一些足够复杂的代码,并且测试套件 可以在不崩溃的情况下报告该故障。我们可以通过重写来强制失败 它:

TEST(test_dref_2,will_not_segfault)
{
    ASSERT_EXIT((deref(nullptr),exit(0)),::testing::ExitedWithCode(0),".*");
}

然后测试测试报告为:

$ ./tester
[==========] Running 2 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 1 test from test_deref_1
[ RUN      ] test_deref_1.will_segfault
[       OK ] test_deref_1.will_segfault (147 ms)
[----------] 1 test from test_deref_1 (147 ms total)

[----------] 1 test from test_dref_2
[ RUN      ] test_dref_2.will_not_segfault
main.cpp:25: Failure
Death test: (deref(nullptr),exit(0))
    Result: died but not with expected exit code:
            Terminated by signal 11 (core dumped)
Actual msg:
[  DEATH   ] 
[  FAILED  ] test_dref_2.will_not_segfault (90 ms)
[----------] 1 test from test_dref_2 (90 ms total)

[----------] Global test environment tear-down
[==========] 2 tests from 2 test cases ran. (237 ms total)
[  PASSED  ] 1 test.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] test_dref_2.will_not_segfault

 1 FAILED TEST

the documentation of {ASSERT|EXPECT}_EXIT 了解这些宏。