// sqrt.cpp #include"sqrt.h" // Get the Square root of a number. doublesquareRoot(constdouble a) { double b = sqrt(a); if(b != b) return-1.0;// NaN check elsereturnsqrt(a); }
EXPECT_* versions generate nonfatal failures, which
don’t abort the current function. Usually EXPECT_* are
preferred, as they allow more than one failure to be reported in a test.
However, you should use ASSERT_* if it doesn’t make sense
to continue when the assertion in question fails.*
# test add_library(mysqrt sqrt.cpp) add_executable(mytest sqrt_test.cpp) target_link_libraries(mytest mysqrt GTest::gtest GTest::gtest_main)
然后运行测试程序也很简单
1 2 3
mkdir build && cd build cmake -DGTEST_ROOT=/Users/hui/Code/googletest/install .. # 改为你的gtest安装路径 make -j32
运行mytest可执行文件后,输出应该类似下面的样子:
1 2 3 4 5 6 7 8 9 10 11 12 13
$ ./mytest [==========] Running 2 tests from 1 test suite. [----------] Global test environment set-up. [----------] 2 tests from SquareRootTest [ RUN ] SquareRootTest.PositiveNos [ OK ] SquareRootTest.PositiveNos (0 ms) [ RUN ] SquareRootTest.NegativeNos [ OK ] SquareRootTest.NegativeNos (0 ms) [----------] 2 tests from SquareRootTest (0 ms total)
[----------] Global test environment tear-down [==========] 2 tests from 1 test suite ran. (0 ms total) [ PASSED ] 2 tests.
$ ./mytest [==========] Running 2 tests from 2 test suites. [----------] Global test environment set-up. Global SetUp called [----------] 1 test from TestSuite1 [ RUN ] TestSuite1.Foo [ OK ] TestSuite1.Foo (0 ms) [----------] 1 test from TestSuite1 (0 ms total)
[----------] 1 test from TestSuite2 [ RUN ] TestSuite2.Foo [ OK ] TestSuite2.Foo (0 ms) [----------] 1 test from TestSuite2 (0 ms total)
[----------] Global test environment tear-down Global TearDown called [==========] 2 tests from 2 test suites ran. (0 ms total) [ PASSED ] 2 tests.