使用Google Test的一个简单例子
0.?引子
?
本例是從?gtest-1.5.0?自帶的?sample?中的?sample1?改寫而來,筆者只添加了一個求?n?的階層的函數,如下。
void?Factorial(int?n,?int?&?result?)
{
????result = 1;
????for?(int?i = 1; i <= n; i++)
????????result *= i;
}
目的是想測試像這樣將返回值放在參數中返回的函數。
對于該函數,添加的單元測試代碼如下。
TEST?(FactorialTest?,?Mytest?)
{
????int?result = 0;
????Factorial?(5, result);
????EXPECT_EQ?(120, result);
}
1.?要測試的代碼
?
要測試的代碼?(Sample.h)?代碼如下。
[c-sharp]?view plaincopy
要測試的代碼?(Sample.cpp)?代碼如下。
[cpp]?view plaincopy
2.?單元測試代碼
?
單元測試代碼?(test.cpp)?如下。
[cpp]?view plaincopy
3.?編譯
?
3.1 Linux?平臺
?
makefile?文件,請參考?“?Linux平臺如何編譯使用Google test寫的單元測試??”
?
3.2 Win32?平臺
?
Make.bat?文件,請參考?“?Win32?平臺如何編譯使用?Google test?編?寫的單元測試??”?。
?
4.?運行結果
?
4.1 Linux?平臺
?
運行結果如下。
# ./test
Running main() from gtest_main.cc
[==========] Running 7 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 4 tests from FactorialTest
[ RUN??????] FactorialTest.Negative
[???????OK ] FactorialTest.Negative (0 ms)
[ RUN??????] FactorialTest.Zero
[???????OK ] FactorialTest.Zero (0 ms)
[ RUN??????] FactorialTest.Positive
[???????OK ] FactorialTest.Positive (0 ms)
[ RUN??????] FactorialTest.Mytest
[???????OK ] FactorialTest.Mytest (0 ms)
[----------] 4 tests from FactorialTest (0 ms total)
?
[----------] 3 tests from IsPrimeTest
[ RUN??????] IsPrimeTest.Negative
[???????OK ] IsPrimeTest.Negative (0 ms)
[ RUN??????] IsPrimeTest.Trivial
[???????OK ] IsPrimeTest.Trivial (0 ms)
[ RUN??????] IsPrimeTest.Positive
[???????OK ] IsPrimeTest.Positive (0 ms)
[----------] 3 tests from IsPrimeTest (0 ms total)
?
[----------] Global test environment tear-down
[==========] 7 tests from 2 test cases ran. (0 ms total)
[??PASSED??] 7 tests.
7?個測試均通過。
?
4.2 Win32?平臺
?
運行結果如下。
?
?
總結
以上是生活随笔為你收集整理的使用Google Test的一个简单例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS2010中使用gtest简单案例
- 下一篇: 同一进程中的线程究竟共享哪些资源