SlideShare a Scribd company logo
1 of 138
Using the Google unit test framework  (aka Google Test) Thierry GAYET
PLAN ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Introduction
Unit Testing definition : “ A unit test is a test of behaviour (normally functional) whose success or failure is wholly determined by the correctness of the test and the correctness of the unit under test.  Thus the unit under test has no external dependencies across boundaries of trust or control, which could introduce other sources of failure.  Such external dependencies include networks, databases, files, registries, clocks and user interfaces.” What is an unit test ?
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Another testing framework?
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Project history
Why unit tests? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
But I don’t have time for tests… ,[object Object],[object Object],[object Object],[object Object],[object Object]
Writing tests = time for more feature work ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Without adequate tests… ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Small tests, not large tests ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Getting back on track ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Test-driven development (TDD) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
So, why Google Test? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Features of Google test framework ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Live demo ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Gtest in detail step by step
Google Test basics ,[object Object],[object Object],[object Object],Test Program Test Test Test Test Test Test
Simple tests ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Reusing the same data configuration ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Google Test is organic ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What to test for: good and bad input ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Death Tests ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Death Tests : example 1/2 #include <gtest/gtest.h> // ******** DEATH TESTS ******** void dieWithExitCode(int exitCode, const std::string& msg) { std::cerr << msg; exit(exitCode); } TEST(ExitCodeDeathTest, processShouldExitWithCorrectCode) { EXPECT_EXIT(dieWithExitCode(5, &quot;Fatal error processing request&quot;), ::testing::ExitedWithCode(5), &quot;error&quot;); } TEST(ExitCodeDeathTest, failsWhenProcessExitsWithIncorrectCode) { EXPECT_EXIT(dieWithExitCode(4, &quot;Fatal error processing request&quot;), ::testing::ExitedWithCode(5), &quot;error&quot;); } TEST(ExitCodeDeathTest, failsWhenProcessExitsWithIncorrectMsg) { EXPECT_EXIT(dieWithExitCode(5, &quot;Unable to process request&quot;), ::testing::ExitedWithCode(5), &quot;error&quot;); } // ******** DEATH TESTS FOR NON-ZERO EXIT CODE ******** TEST(ExitCodeDeathTest, processShouldExitWithNonZeroCode) { EXPECT_DEATH(dieWithExitCode(5, &quot;Fatal error processing request&quot;), &quot;error&quot;); } TEST(ExitCodeDeathTest, failsWhenProcessExitsWithCodeZero) { EXPECT_DEATH(dieWithExitCode(0, &quot;Fatal error processing request&quot;), &quot;error&quot;); }
Death Tests : example 2/2 TEST(ExitCodeDeathTest, failsWhenProcessExitsWithNonZeroCodeButIncorrectMsg) { EXPECT_DEATH(dieWithExitCode(5, &quot;Unable to process request&quot;), &quot;error&quot;); } // ********* HOME GROWN PREDICATES ******* class ExitCodeRangeCheck { public: ExitCodeRangeCheck(int min_, int max_) : min(min_), max(max_) { } bool operator()(int exitCode) { return (exitCode >= min) && (exitCode <= max); } private: const int min; const int max; }; TEST(ExitCodeDeathTest, processExitCodeShouldBeInRangeNoRegex) { EXPECT_EXIT(dieWithExitCode(5, &quot;Fatal error processing request&quot;), ExitCodeRangeCheck(2,7), &quot;&quot;); } TEST(ExitCodeDeathTest, processExitCodeShouldBeInRangeAnyChars) { EXPECT_EXIT(dieWithExitCode(5, &quot;Fatal error processing request&quot;), ExitCodeRangeCheck(2,7), &quot;.*&quot;); } TEST(ExitCodeDeathTest, processExitCodeShouldBeOutOfRangeAnyChars) { EXPECT_EXIT(dieWithExitCode(1, &quot;Fatal error processing request&quot;), ExitCodeRangeCheck(2,7), &quot;.*&quot;); }
What not to test? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How many tests are enough? ,[object Object],[object Object]
Make your code testable ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Dependency injection ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
What makes good tests? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Favor small test functions ,[object Object],[object Object],[object Object],[object Object],[object Object]
Make the messages informative ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
EXPECT vs ASSERT ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Summary of the gtest ,[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Runtime controls 1/2
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Runtime controls 2/2
Gtest with  language C
Usage of gtest with C language ,[object Object],[object Object],[object Object],[object Object],[object Object]
Architecture of the example Libgm_os gtest gTest_gm_os_posix gtest.pc gtest.so include/ Libgm_os.a include/ Example of a gtest usage. gtest Installation on the stagingdir   pkgconfig  compilation link Binary test based on gtest   Library to test  
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Dependencies
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Symbols of the gmos_gtest binary
Beginning of the test class /* System header */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Local header */ #include “gm_os.h&quot; /* Google test header */ #include <gtest/gtest.h> namespace  RevolutionS { /** * @brief C++ Class defined for wrapping the unit test */ class  GM_OS_TestSuite  : public ::testing::Test { protected: GM_OS_TestSuite () { printf( “GM_OS_TestSuite - Constructor&quot; ); g_exit_thread = false; g_exit_main  = false; } /* GM_OS_TestSuite */
...end of the test class // You can do clean-up work that doesn't throw exceptions here. virtual ~ GM_OS_TestSuite () { printf( “GM_OS_TestSuite - Destructor&quot; ); } /* ~GM_OS_TestSuite */ // Code here will be called immediately after the constructor (right before each test). virtual void SetUp() { printf(“GM_OS_TestSuite - initialisation of the environment &quot;); /* Launch the GM_OS init function */ } /* SetUp */ // Code here will be called immediately after each test (right before the destructor). virtual void TearDown() { printf(“GM_OS_TestSuite - cleaning the environment &quot; ); } /* TearDown */ };
The unitary tests TEST_F(  GM_OS_TestSuite , the_unix_pthread_should_start) { EtPl_OS_ThreadId myThread_id; EXPECT_EQ( 0, EtPl_OS_ThreadCreate(myfuncThread, NULL,       NULL,     4096,     63,     &quot;mon thread&quot;,   &myThread_id) ); } TEST_F(  GM_OS_TestSuite , give_the_delay_between_two_times ) { GM_OS_Time  starttime  = 0; GM_OS_Time  endtime  = 45; GM_OS_Time  delayExpected = 45; EXPECT_EQ( delayExpected, GM_OS_TimeCalculateDelay(starttime, endtime) ); } (...) // put other test case here ... (...) } /* Namespace */
The main function int main(int argc, char* argv[], char* env[]) { int rcmain    = 0; int main_heap_size  = 800*1024; /* OOM_DEFAULT_ET_MAIN_HEAP_SIZE : 800ko */ int  nb_max_heaps  = 48; /* OOM_DEFAULT_ET_NB_MAX_HEAPS  */ int  et_central_thread_priority = -1; /*    */ /* -------------------------------------------- */ /*  Set the gtest's context  */ /* -------------------------------------------- */ ::testing::GTEST_FLAG(color)  = &quot;yes&quot;; ::testing::GTEST_FLAG(print_time) = true; ::testing::GTEST_FLAG(output)  = &quot;xml:junit_export.xml&quot;; /* -------------------------------------------- */ /*  Initialize and prepare the tests  */ /* -------------------------------------------- */ ::testing::InitGoogleTest(&argc, argv); GM_OS_Init( main_heap_size,    nb_max_heaps,  et_central_thread_priority ); /* -------------------------------------------- */ /*  Run all the tests  */ /* -------------------------------------------- */ rcmain = RUN_ALL_TESTS(); return rcmain; } /* main */
Build $ make g++ -DPACKAGE_NAME=amp;quot;libetpl_oss_posixamp;quot; -DPACKAGE_TARNAME=GM_OSamp;quot; -DPACKAGE_VERSION=amp;quot;1.0.0amp;quot; -DPACKAGE_STRING=GM_OS1.0.0amp;quot; -DPACKAGE_BUGREPORT=amp;quot;thierry.gayet2@technicolor.comamp;quot; -DPACKAGE_URL=amp;quot;amp;quot; -DPACKAGE=GM_OSamp;quot; -DVERSION=amp;quot;1.0.0amp;quot; -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_DLFCN_H=1 -DLT_OBJDIR=amp;quot;.libs/amp;quot; -I.  -I/local/home/gayetth/bck_revolution/revolution/target/usr/local/include/  -I/local/home/gayetth/bck_revolution/revolution/target/usr/local/include/uno  -I../include -I./include -I../src/os -I../include  -g -O2 -Wall -O2 -MT gtest_etpl_oss_posix-gtest_unit_os.o -MD -MP -MF .deps/gtest_etpl_oss_posix-gtest_unit_os.Tpo -c -o gtest_etpl_oss_posix-gtest_unit_os.o `test -f 'src/gtest_unit_os.cpp' || echo './'`src/gtest_unit_os.cpp mv -f .deps/gtest_etpl_oss_posix-gtest_unit_os.Tpo .deps/gtest_etpl_oss_posix-gtest_unit_os.Po /bin/bash ../libtool --tag=CXX  --mode=link g++  -g -O2 -Wall -O2 ../src/.libs/libetpl_oss_posix.a  -o gtest_etpl_oss_posix gtest_etpl_oss_posix-gtest_unit_os.o  -L/local/home/gayetth/bck_revolution/revolution/target/usr/local/lib -lgtest  -L/local/home/gayetth/bck_revolution/revolution/target/usr/local/lib -luno  libtool: link: g++ -g -O2 -Wall -O2 -o gtest_etpl_oss_posix gtest_etpl_oss_posix-gtest_unit_os.o  ../src/.libs/libetpl_oss_posix.a -L/local/home/gayetth/bck_revolution/revolution/target/usr/local/lib /local/home/gayetth/gayetth@141.11.146.121/target/usr/local/lib/libgtest.so /local/home/gayetth/gayetth@141.11.146.121/target/usr/local/lib/libuno.so -pthread -Wl,-rpath -Wl,/local/home/gayetth/gayetth@141.11.146.121/target/usr/local/lib -Wl,-rpath -Wl,/local/home/gayetth/gayetth@141.11.146.121/target/usr/local/lib ( … )
Launching the tests ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Junit xml export <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <testsuites tests=&quot;24&quot; failures=&quot;0&quot; disabled=&quot;0&quot; errors=&quot;0&quot; time=&quot;0.001&quot; name=&quot;AllTests&quot;> <testsuite name=&quot;GM_OS_TestSuite&quot; tests=&quot;24&quot; failures=&quot;0&quot; disabled=&quot;0&quot; errors=&quot;0&quot; time=&quot;0.001&quot;> <testcase name=&quot;the_unix_semaphore_should_lock&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;should_wait_for_a_semaphore_with_timeout&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;should_send_a_signal_to_the_semaphore&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;the_unix_semaphore_should_remove_a_semaphore_just_initialized&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;create_a_mutex&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;lock_a_mutex&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;unlock_a_mutex&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;remove_a_mutex&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;add_a_delay_to_a_time&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;give_the_delay_between_two_times&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;get_the_current_posix_time&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;set_then_get_the_current_utc_time&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;datetime_and_string_conversion&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;create_a_new_message_queue&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;remove_a_message_queue&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;create_a_new_heap&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;remove_a_heap&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;allocate_some_memory&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;get_size_free_memory&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;get_size_free_block&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;the_unix_pthread_should_start&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;Increase_an_atomic_variable&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;Decrease_an_atomic_variable&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;Set_a_variable_not_atomic_yet&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> </testsuite> </testsuites> Sample of xml export automatically generated: That can be imported into Hudson as is.
configure.ac of this example dnl Brief  : configure for my Package dnl Team  : Revolution-S - Rennes AC_PREREQ(2.59) m4_define([my_package_major_version], [1]) m4_define([my_package_minor_version], [0]) m4_define([my_package_micro_version], [0]) m4_define([my_package_version], [my_package_major_version. my_package_minor_version. my_package_micro_version]) AC_INIT([my_package], [my_package_version], [thierry.gayet2@technicolor.com]) (...) AC_ARG_ENABLE(test, AS_HELP_STRING([--enable-test], [Enable the test unitary support [default=no]]), [case &quot;${enableval}&quot; in yes) have_test=true ;; no)  have_test=false ;; *)  AC_MSG_ERROR(bad value ${enableval} for --enable-test) ;; esac], [have_test=false]) AM_CONDITIONAL(HAVE_TEST, $have_test) AC_MSG_CHECKING(Checking the test support) if test &quot;$have_test&quot; != &quot;false&quot; ; then AC_MSG_RESULT([yes])  PKG_CHECK_MODULES([GTEST],[gtest],[have_libgtest=yes],[have_libgtest=no]) if test &quot;$have_libgtest&quot; = no ; then AC_MSG_ERROR([Missing libgtest library (http://code.google.com/p/googletest/) !!]) fi Else AC_MSG_RESULT([no]) fi (...) AC_OUTPUT(unit_test/Makefile)
Makefile.am of this example # # Makefile for the unit test based on Google Test framework # (...) if  HAVE_TEST TESTS    =  gmos_gtest else TESTS    = endif noinst_PROGRAMS  = $(TESTS) gmos_gtest _SOURCES  = $(top_srcdir)/unit_test/src/test_gm_os.cpp gmos_gtest _CPPFLAGS  = -I$(HEADER_DIR) $(GTEST_CFLAGS)  gmos_gtest _LDFLAGS  = $(top_srcdir)/.libs/libgm_os.a -lpthread gmos_gtest _LDADD  = $(GTEST_LIBS) # # END OF FILE #
Gtest with  language C++
Explicit Success and Failure ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Exception Assertions These are for verifying that a piece of code throws (or does not throw) an exception of the given type:  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Fatal assertion Nonfatal assertion Verifies ASSERT_THROW(statement, exception_type); EXPECT_THROW(statement, exception_type); statement  throws an exception of the given type ASSERT_ANY_THROW(statement); EXPECT_ANY_T ROW(statement); statement throws an exception of any type  ASSERT_NO_THROW(statement); EXPECT_NO_THROW(statement); statement doesn't throw any exception
Predicate Assertions for Better Error Messages Even though Google Test has a rich set of assertions, they can never be complete, as it's impossible (nor a good idea) to anticipate all the scenarios a user might run into.  Therefore, sometimes a user has to use EXPECT_TRUE()  to check a complex expression, for lack of a better macro.  This has the problem of not showing you the values of the parts of the expression, making it hard to understand what went wrong.  As a workaround, some users choose to construct the failure message by themselves, streaming it into EXPECT_TRUE().  However, this is awkward especially when the expression has side-effects or is expensive to evaluate.
#include <gtest/gtest.h> class MyException : public std::exception { public: MyException(const char* message) : std::exception(message) {} }; void methodThatThrows() { throw MyException(&quot;Exception&quot;); } void methodThatDoesNotThrow() { } TEST(ExceptionTest, ensureSpecificExceptionIsThrown) { EXPECT_THROW(methodThatThrows(), MyException); } TEST(ExceptionTest, ensureExceptionThrownHasExectedBaseClass) { EXPECT_THROW(methodThatThrows(), std::exception); } TEST(ExceptionTest, ensureSomeExceptionIsThrown) { EXPECT_ANY_THROW(methodThatThrows()); } TEST(ExceptionTest, ensureNoExceptionIsThrown) { EXPECT_NO_THROW(methodThatDoesNotThrow()); } Predicate Assertions for Better Error Messages Example 1
Predicate Assertions for Better Error Messages Example 2 – 1/2 #include <gtest/gtest.h> void method1() {} void method2() {} void method3() {} TEST(StructuringTests, canUseCompoundStatementsInThrowAssertions) { ASSERT_NO_THROW( method1(); method2(); method3(); ); } //********** SCOPED TRACE *********** void checkRange(int min, int max, int actual) { ASSERT_LE(min, actual) << &quot;Actual is less than minimum&quot;; ASSERT_GE(max, actual) << &quot;Actual is greater than maximum&quot;; } void checkAgeEligibility(int age) { SCOPED_TRACE(&quot;Age eligibility&quot;); checkRange(25, 39, age); } void checkIncomeEligibility(int salary) { SCOPED_TRACE(&quot;Salary eligibility&quot;); checkRange(20, 45, salary); }
Predicate Assertions for Better Error Messages Example 2 – 2/2 void promotionEligibilityTest(int salary, int age) { checkAgeEligibility(age); checkIncomeEligibility(salary); } TEST(StructuringTests, checkIsEligibleForMarketingPromotion) { promotionEligibilityTest(30, 22); } // ********** FATAL FAILURES **************** TEST(StructuringTests, checksAllEligibilityCriteriaEvenAfterFailure) { checkAgeEligibility(2); checkIncomeEligibility(2); } TEST(StructuringTests, onlyChecksEligibilityCriteriaIfNoFailure_1) { ASSERT_NO_FATAL_FAILURE(checkAgeEligibility(2)); ASSERT_NO_FATAL_FAILURE(checkIncomeEligibility(2)); } TEST(StructuringTests, onlyChecksEligibilityCriteriaIfNoFailure_2) { checkAgeEligibility(2); if (!HasFatalFailure()) { checkIncomeEligibility(2); } // Also available: // - HasNonfatalFailure // - HasFailure (fatal or non-fatal) }
Using an Existing Boolean Function If you already have a function or a functor that returns bool (or a type that can be implicitly converted to bool), you can use it in a predicate assertion to get the function arguments printed for free:  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Fatal assertion Nonfatal assertion Verifies ASSERT_PRED1(pred1, val1); EXPECT_PRED1(pred1, val1); pred1(val1)  returns true ASSERT_PRED2(pred2, val1, val2); EXPECT_PRED2(pred2, val1, val2); pred2(val1, val2) returns true
Using a Function That Returns an AssertionResult  1/3 While EXPECT_PRED*() and friends are handy for a quick job, the syntax is not satisfactory: you have to use different macros for different arities, and it feels more like Lisp than C++. The ::testing::AssertionResult class solves this problem.  An AssertionResult object represents the result of an assertion (whether it's a success or a failure, and an associated message). You can create an AssertionResult using one of these factory functions:  namespace testing  { // Returns an AssertionResult object to indicate that an assertion has // succeeded. AssertionResult AssertionSuccess(); // Returns an AssertionResult object to indicate that an assertion has failed. AssertionResult AssertionFailure(); } You can then use the << operator to stream messages to the AssertionResult object.
Using a Function That Returns an AssertionResult  2/3 To provide more readable messages in Boolean assertions (e.g. EXPECT_TRUE()), write a predicate function that returns AssertionResult instead of bool. For example, if you define IsEven() as: ::testing::AssertionResult IsEven(int n)  {    if ((n % 2) == 0)      return ::testing::AssertionSuccess();    else      return ::testing::AssertionFailure() << n << &quot; is odd&quot;; } Instead of:  bool IsEven(int n)  {    return (n % 2) == 0; } The failed assertion EXPECT_TRUE(IsEven(Fib(4))) will print:  Value of: IsEven(Fib(4)) Actual: false (3 is odd) Expected: true
Using a Function That Returns an AssertionResult  3/3 Instead of a more opaque : Value of: IsEven(Fib(4)) Actual: false Expected: true If you want informative messages in EXPECT_FALSE and ASSERT_FALSE as well, and are fine with making the predicate slower in the success case, you can supply a success message: ::testing::AssertionResult IsEven(int n)  {    if ((n % 2) == 0)      return ::testing::AssertionSuccess() << n << &quot; is even&quot;;    else      return ::testing::AssertionFailure() << n << &quot; is odd&quot;; } Then the statement EXPECT_FALSE(IsEven(Fib(6))) will print : Value of: IsEven(Fib(6)) Actual: true (8 is even) Expected: false ,[object Object]
Using a Predicate-Formatter  1/3 If you find the default message generated by (ASSERT|EXPECT)_PRED* and (ASSERT|EXPECT)_(TRUE|FALSE) unsatisfactory, or some arguments to your predicate do not support streaming to ostream, you can instead use the following predicate-formatter assertions to fully customize how the message is formatted: The difference between this and the previous two groups of macros is that instead of a predicate, (ASSERT|EXPECT)_PRED_FORMAT* take a predicate-formatter (pred_formatn), which is a function or functor with the signature:  ::testing::AssertionResult PredicateFormattern(const char* expr1, const char* expr2, ... const char* exprn, T1 val1, T2 val2, ... Tn valn);  where val1, val2, ..., and valn are the values of the predicate arguments, and expr1, expr2, ..., and exprn are the corresponding expressions as they appear in the source code. The types T1, T2, ..., and Tn can be either value types or reference types. For example, if an argument has type Foo, you can declare it as either Foo or const Foo&, whichever is appropriate.  Fatal assertion Nonfatal assertion Verifies ASSERT_PRED_FORMAT1(pred_format1, val1); EXPECT_PRED_FORMAT1(pred_format1, val1`);  pred_format1(val1) is successful  ASSERT_PRED_FORMAT2(pred_format2, val1, val2); EXPECT_PRED_FORMAT2(pred_format2, val1, val2); pred_format2(val1, val2) is successful
Using a Predicate-Formatter  2/3 A predicate-formatter returns a ::testing::AssertionResult object to indicate whether the assertion has succeeded or not. The only way to create such an object is to call one of these factory functions:  As an example, let's improve the failure message in the previous example, which uses EXPECT_PRED2():  // Returns the smallest prime common divisor of m and n, // or 1 when m and n are mutually prime. int SmallestPrimeCommonDivisor(int m, int n) { ... } // A predicate-formatter for asserting that two integers are mutually prime. ::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,                                                 const char* n_expr,                                                 int m,                                                 int n)  {    if (MutuallyPrime(m, n))      return ::testing::AssertionSuccess();      return ::testing::AssertionFailure()        << m_expr << &quot; and &quot; << n_expr << &quot; (&quot; << m << &quot; and &quot; << n        << &quot;) are not mutually prime, &quot; << &quot;as they have a common divisor &quot;        << SmallestPrimeCommonDivisor(m, n); } With this predicate-formatter, we can use:  EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);
Using a Predicate-Formatter  3/3 ,[object Object],[object Object],[object Object],[object Object]
Using a Predicate-Formatter  : example 1/2 static const int SALARY(20000); static const int MORTGAGE(100000); const int GENEROUS_MULTIPLIER(5); const int STANDARD_MULTIPLIER(4); // ********** EXPLICIT EXPECTATION *********** TEST(ExpectationFailureTests, canTestExplicitlyForResult) { EXPECT_TRUE(earnsEnoughToAffordMortgage(SALARY, MORTGAGE, GENEROUS_MULTIPLIER)); //EXPECT_FALSE(earnsEnoughToAffordMortgage(SALARY, MORTGAGE, STANDARD_MULTIPLIER)); EXPECT_TRUE(earnsEnoughToAffordMortgage(SALARY, MORTGAGE, STANDARD_MULTIPLIER)) << &quot;Fails affordability test&quot;; } // ********** PREDICATED EXPECTATION *********** TEST(ExpectationFailureTests, canImproveTestsTernaryPredicate) { EXPECT_PRED3(earnsEnoughToAffordMortgage, SALARY, MORTGAGE, STANDARD_MULTIPLIER); } // ********** FORMATTED PREDICATE *********** ::testing::AssertionResult checkAffordability( const char* salary_text, const char* mortgage_text, const char* multiplier_text, int salary, int mortgage, int multiplier) { int maxLoanAmount = salary * multiplier; if (maxLoanAmount >= mortgage) { return ::testing::AssertionSuccess(); } else {
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Using a Predicate-Formatter  : example 2/2
Floating-Point Comparison ,[object Object],[object Object],[object Object]
Floating-Point Macros ,[object Object],[object Object],[object Object],Fatal assertion Nonfatal assertion Verifies ASSERT_NEAR(val1, val2, abs_error); EXPECT_NEAR(val1, val2, abs_error); the difference between val1 and val2 doesn't exceed the given absolute error  Fatal assertion Nonfatal assertion Verifies ASSERT_FLOAT_EQ(expected, actual); EXPECT_FLOAT_EQ(expected, actual); the two float values are almost equal  ASSERT_DOUBLE_EQ(expected, actual); EXPECT_DOUBLE_EQ(expected, actual); the two double values are almost equal
Floating-Point Predicate-Format Functions¶ ,[object Object],[object Object],[object Object],EXPECT_PRED_FORMAT2(::testing::FloatLE, val1, val2); EXPECT_PRED_FORMAT2(::testing::DoubleLE, val1, val2);
TEST(FloatingPoint, shouldTestToAcceptablePrecision) { double d1 = 1.0 / 999999999.99999999999; double d2 = 1.0 / 999999999.999999; EXPECT_EQ(d1, d2); EXPECT_DOUBLE_EQ(d1, d2); EXPECT_NEAR(d1, d2, 0.000001); } Floating-Point Predicate-Format Functions¶
Windows HRESULT assertions ,[object Object],The generated output contains the human-readable error message associated with the HRESULT code returned by expression.  You might use them like this:  ,[object Object],CComPtr shell; ASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L&quot;Shell.Application&quot;)); CComVariant empty; ASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty)); Fatal assertion Nonfatal assertion Verifies ASSERT_HRESULT_SUCCEEDED(expression); EXPECT_HRESULT_SUCCEEDED(expression); expression is a success HRESULT ASSERT_HRESULT_FAILED(expression); EXPECT_HRESULT_FAILED(expression); expression is a failure HRESULT
Type Assertions ,[object Object],to assert that types T1 and T2 are the same. The function does nothing if the assertion is satisfied. If the types are different, the function call will fail to compile, and the compiler error message will likely (depending on the compiler) show you the actual values of T1 and T2. This is mainly useful inside template code.  Caveat: When used inside a member function of a class template or a function template, StaticAssertTypeEq<T1, T2>() is effective only if the function is instantiated. For example, given:  ::testing::StaticAssertTypeEq<T1, T2>(); template <typename T> class Foo  {   public:    void Bar() { ::testing::StaticAssertTypeEq<int, T>(); } }; the code:  void Test1() { Foo<bool> foo; } will not generate a compiler error, as Foo<bool>::Bar() is never actually instantiated. Instead, you need:  void Test2() { Foo<bool> foo; foo.Bar(); } ,[object Object],[object Object]
Assertion Placement You can use assertions in any C++ function. In particular, it doesn't have to be a method of the test fixture class. The one constraint is that assertions that generate a fatal failure (FAIL* and ASSERT_*) can only be used in void-returning functions. This is a consequence of Google Test not using exceptions. By placing it in a non-void function you'll get a confusing compile error like &quot;error: void value not ignored as it ought to be&quot;.  If you need to use assertions in a function that returns non-void, one option is to make the function return the value in an out parameter instead.  For example, you can rewrite T2 Foo(T1 x) to void Foo(T1 x, T2* result). You need to make sure that *result contains some sensible value even when the function returns prematurely. As the function now returns void, you can use any assertion inside of it.  If changing the function's type is not an option, you should just use assertions that generate non-fatal failures, such as ADD_FAILURE* and EXPECT_*.  Note: Constructors and destructors are not considered void-returning functions, according to the C++ language specification, and so you may not use fatal assertions in them.  You'll get a compilation error if you try. A simple workaround is to transfer the entire body of the constructor or destructor to a private void-returning method. However, you should be aware that a fatal assertion failure in a constructor does not terminate the current test, as your intuition might suggest; it merely returns from the constructor early, possibly leaving your object in a partially-constructed state. Likewise, a fatal assertion failure in a destructor may leave your object in a partially-destructed state. Use assertions carefully in these situations!
Teaching Google Test How to Print Your Values When a test assertion such as EXPECT_EQ fails, Google Test prints the argument values to help you debug. It does this using a user-extensible value printer. This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the << operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out. As mentioned earlier, the printer is  extensible . That means you can teach it to do a better job at printing your particular type than to dump the bytes. To do that, define << for your type: #include <iostream> namespace foo { class Bar { ... };  // We want Google Test to be able to print instances of this. // It's important that the << operator is defined in the SAME // namespace that defines Bar.  C++'s look-up rules rely on that. ::std::ostream& operator<<(::std::ostream& os, const Bar& bar) {   return os << bar.DebugString();  // whatever needed to print bar to os } }  // namespace foo  Sometimes, this might not be an option: your team may consider it bad style to have a << operator for Bar, or Bar may already have a << operator that doesn't do what you want (and you cannot change it). If so, you can instead define a PrintTo() function like this:
Teaching Google Test How to Print Your Values #include <iostream> namespace foo  { class Bar { ... }; // It's important that PrintTo() is defined in the SAME // namespace that defines Bar.  C++'s look-up rules rely on that. void PrintTo(const Bar& bar, ::std::ostream* os)  {   *os << bar.DebugString();  // whatever needed to print bar to os } }  // namespace foo If you have defined both << and PrintTo(), the latter will be used when Google Test is concerned. This allows you to customize how the value appears in Google Test's output without affecting code that relies on the behavior of its << operator. If you want to print a value x using Google Test's value printer yourself, just call ::testing::PrintToString( x ), which returns anstd::string: vector<pair<Bar, int> > bar_ints = GetBarIntVector(); EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))     << &quot;bar_ints = &quot; << ::testing::PrintToString(bar_ints);
How to Write a Death Test ,[object Object],where statement is a statement that is expected to cause the process to die, predicate is a function or function object that evaluates an integer exit status, and regex is a regular expression that the stderr output of statement is expected to match. Note that statement can be any valid statement (including compound statement) and doesn't have to be an expression.  As usual, the ASSERT variants abort the current test function, while the EXPECT variants do not.  Fatal assertion Nonfatal assertion Verifies ASSERT_DEATH(statement, regex`);  EXPECT_DEATH(statement, regex`);  statement crashes with the given error  ASSERT_DEATH_IF_SUPPORTED(statement, regex`);  EXPECT_DEATH_IF_SUPPORTED(statement, regex`);  if death tests are supported, verifies that statement crashes with the given error; otherwise verifies nothing  ASSERT_EXIT(statement, predicate, regex`);  EXPECT_EXIT(statement, predicate, regex`); statement exits with the given error and its exit code matches predicate
How to Write a Death Test Note : We use the word &quot;crash&quot; here to mean that the process terminates with a non-zero exit status code. There are two possibilities: either the process has called exit() or _exit() with a non-zero value, or it may be killed by a signal. This means that if statement terminates the process with a 0 exit code, it is not considered a crash by EXPECT_DEATH. Use EXPECT_EXIT instead if this is the case, or if you want to restrict the exit code more precisely. A predicate here must accept an int and return a bool. The death test succeeds only if the predicate returns true. Google Test defines a few predicates that handle the most common cases:  This expression is true if the program exited normally with the given exit code.  ::testing::ExitedWithCode(exit_code) ::testing::KilledBySignal(signal_number)  // Not available on Windows. This expression is true if the program was killed by the given signal.  The *_DEATH macros are convenient wrappers for *_EXIT that use a predicate that verifies the process' exit code is non-zero.
How to Write a Death Test Note that a death test only cares about three things:  1. does statement abort or exit the process?    2. (in the case of ASSERT_EXIT and EXPECT_EXIT) does the exit status satisfy predicate? Or (in the case of ASSERT_DEATH and EXPECT_DEATH) is the exit status non-zero? And    3. does the stderr output match regex?  In particular, if statement generates an ASSERT_* or EXPECT_* failure, it will not cause the death test to fail, as Google Test assertions don't abort the process.  To write a death test, simply use one of the above macros inside your test function. For example,  TEST(My*DeathTest*, Foo)  {    // This death test uses a compound statement.    ASSERT_DEATH({ int n = 5; Foo(&n); }, &quot;Error on line .* of Foo()&quot;); } TEST(MyDeathTest, NormalExit) {    EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), &quot;Success&quot;); } TEST(MyDeathTest, KillMyself) {    EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), &quot;Sending myself unblockable signal&quot;); }
How to Write a Death Test It verifies that:  1. calling Foo(5) causes the process to die with the given error message,    2. calling NormalExit() causes the process to print &quot;Success&quot; to stderr and exit with exit code 0, and  3. calling KillMyself() kills the process with signal SIGKILL.  The test function body may contain other assertions and statements as well, if necessary.  Important: We strongly recommend you to follow the convention of naming your test case (not test) *DeathTest when it contains a death test, as demonstrated in the above example. The Death Tests And Threads section below explains why.  If a test fixture class is shared by normal tests and death tests, you can use typedef to introduce an alias for the fixture class and avoid duplicating its code:  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Regular Expression Syntax On POSIX systems (e.g. Linux, Cygwin, and Mac), Google Test uses the  POSIX extended regular expression  syntax in death tests. To learn about this syntax, you may want to read this  Wikipedia entry .  On Windows, Google Test uses its own simple regular expression implementation. It lacks many features you can find in POSIX extended regular expressions. For example, we don't support union (&quot;x|y&quot;), grouping (&quot;(xy)&quot;), brackets (&quot;[xy]&quot;), and repetition count (&quot;x{5,7}&quot;), among others. Below is what we do support (A denotes a literal character, period (.), or a single  escape sequence; x and y denote regular expressions.):  ,[object Object],[object Object],[object Object]
How It Works ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Death Tests And Threads ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Death Test Styles ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Caveats ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Using Assertions in Sub-routines Adding Traces to Assertions If a test sub-routine is called from several places, when an assertion inside it fails, it can be hard to tell which invocation of the sub-routine the failure is from. You can alleviate this problem using extra logging or custom failure messages, but that usually clutters up your tests. A better solution is to use the  SCOPED_TRACE  macro: where  message  can be anything streamable to  std::ostream . This macro will cause the current file name, line number, and the given message to be added in every failure message. The effect will be undone when the control leaves the current lexical scope. ,[object Object],[object Object],[object Object],[object Object],SCOPED_TRACE( message );
Using Assertions in Sub-routines Without the trace, it would've been difficult to know which invocation of Sub1() the two failures come from respectively. (You could add an extra message to each assertion in Sub1() to indicate the value of n, but that's tedious.) Some tips on using SCOPED_TRACE: With a suitable message, it's often enough to use SCOPED_TRACE at the beginning of a sub-routine, instead of at each call site. When calling sub-routines inside a loop, make the loop iterator part of the message in SCOPED_TRACE such that you can know which iteration the failure is from. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for SCOPED_TRACE. You can simply use &quot;&quot;. You can use SCOPED_TRACE in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file! Availability:  Linux, Windows, Mac.
Propagating Fatal Failures ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Asserting on Subroutines As shown above, if your test calls a subroutine that has an  ASSERT_*  failure in it, the test will continue after the subroutine returns. This may not be what you want. Often people want fatal failures to propagate like exceptions. For that Google Test offers the following macros: Only failures in the thread that executes the assertion are checked to determine the result of this type of assertions. If  statement  creates new threads, failures in these threads are ignored. Examples: ASSERT_NO_FATAL_FAILURE(Foo()); int i; EXPECT_NO_FATAL_FAILURE({   i = Bar(); }); Availability:  Linux, Windows, Mac. Assertions from multiple threads are currently not supported. Fatal assertion Nonfatal assertion Verifies ASSERT_NO_FATAL_FAILURE( statement ); EXPECT_NO_FATAL_FAILURE( statement ); statement  doesn't generate any new fatal failures in the current thread.
Checking for Failures in the Current Test HasFatalFailure() in the ::testing::Test class returns true if an assertion in the current test has suffered a fatal failure. This allows functions to catch fatal failures in a sub-routine and return early. class Test {  public:   ...   static bool HasFatalFailure(); }; The typical usage, which basically simulates the behavior of a thrown exception, is: TEST(FooTest, Bar) {   Subroutine();   // Aborts if Subroutine() had a fatal failure.   if (HasFatalFailure())     return;   // The following won't be executed.   ... } If HasFatalFailure() is used outside of TEST() , TEST_F() , or a test fixture, you must add the ::testing::Test:: prefix, as in: if (::testing::Test::HasFatalFailure())   return; Similarly, HasNonfatalFailure() returns true if the current test has at least one non-fatal failure, and HasFailure() returns true if the current test has at least one failure of either kind. Availability:  Linux, Windows, Mac. HasNonfatalFailure() and HasFailure() are available since version 1.4.0.
Logging Additional Information ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Method used for providing data
Sharing Resources Between Tests in the Same Test Case ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Sharing Resources Between Tests in the Same Test Case ,[object Object],[object Object],[object Object]
Global Set-Up and Tear-Down ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Global Set-Up and Tear-Down ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Value Parameterized Tests ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Value Parameterized Tests ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How to Write Value-Parameterized Tests ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How to Write Value-Parameterized Tests Finally, you can use  INSTANTIATE_TEST_CASE_P  to instantiate the test case with any set of parameters you want. Google Test defines a number of functions for generating test parameters. They return what we call (surprise!)  parameter generators . Here is a summary of them, which are all in the testing  namespace: For more details, see the comments at the definitions of these functions in the source code. The following statement will instantiate tests from the  FooTest  test case each with parameter values  &quot;meeny&quot; ,  &quot;miny&quot; , and  &quot;moe&quot; . INSTANTIATE_TEST_CASE_P(InstantiationName,                         FooTest,                         ::testing::Values(&quot;meeny&quot;, &quot;miny&quot;, &quot;moe&quot;));   o distinguish different instances of the pattern (yes, you can instantiate it more than once), the first argument to INSTANTIATE_TEST_CASE_P is a prefix that will be added to the actual test case name.  Remember to pick unique prefixes for different instantiations. The tests from the instantiation above will have these names:  Range(begin, end[, step]) Yields values  {begin, begin+step, begin+step+step, ...} . The values do not include  end .  step  defaults to 1. Values(v1, v2, ..., vN) Yields values  {v1, v2, ..., vN} . ValuesIn(container) and  ValuesIn(begin, end) Yields values from a C-style array, an STL-style container, or an iterator range  [begin, end) . Bool() Yields sequence  {false, true} . Combine(g1, g2, ..., gN) Yields all combinations (the Cartesian product for the math savvy) of the values generated by the  N  generators. This is only available if your system provides the  <tr1/tuple> header. If you are sure your system does, and Google Test disagrees, you can override it by defining  GTEST_HAS_TR1_TUPLE=1 . See comments in  include/gtest/internal/gtest-port.h  for more information.
How to Write Value-Parameterized Tests ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Creating Value-Parameterized Abstract Tests ,[object Object],[object Object],[object Object],[object Object],[object Object]
Typed Tests 1/2 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Typed Tests 2/2 ,[object Object],[object Object],[object Object],[object Object]
TYPED TESTS : example 1/2 #include <gtest/gtest.h> template <typename T> class TypedTests : public ::testing::Test { protected: T t; T t2; }; class MyClass { public: operator int() { throw &quot;Do not convert MyClass to int&quot;; } }; typedef ::testing::Types<char, int, unsigned int, bool, MyClass> TypesToTest; TYPED_TEST_CASE(TypedTests, TypesToTest); TYPED_TEST(TypedTests, implicitlyConvertibleToInt)  { EXPECT_NO_THROW(int i = this->t); }
TYPED TESTS : example 2/2 TYPED_TEST(TypedTests, operatorStarIsSymmetric)  { EXPECT_NO_THROW(   EXPECT_EQ(t*t2, t2*t)   ); } // Inside a test, refer to the special name TypeParam to get the type // parameter.  Since we are inside a derived class template, C++ requires // us to visit the members of FooTest via 'this'. //e.g. TypeParam n = this->value_; // To visit static members of the fixture, add the 'TestFixture::' // prefix. // e.g. n += TestFixture::shared_; // To refer to typedefs in the fixture, add the 'typename TestFixture::' // prefix.  The 'typename' is required to satisfy the compiler. // typename TestFixture::List values; // values.push_back(n);
Type-Parameterized Tests 1/2 ,[object Object],[object Object],[object Object]
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code
Using Google Test framework for unit testing C++ code

More Related Content

What's hot

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
What is JUnit? | Edureka
What is JUnit? | EdurekaWhat is JUnit? | Edureka
What is JUnit? | EdurekaEdureka!
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework OverviewMario Peshev
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Test Automation
Test AutomationTest Automation
Test Automationrockoder
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript FundamentalsSunny Sharma
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaAndrey Kolodnitsky
 

What's hot (20)

Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Clean code
Clean codeClean code
Clean code
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
What is JUnit? | Edureka
What is JUnit? | EdurekaWhat is JUnit? | Edureka
What is JUnit? | Edureka
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Test Automation
Test AutomationTest Automation
Test Automation
 
GMock framework
GMock frameworkGMock framework
GMock framework
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Junit
JunitJunit
Junit
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
BDD with Cucumber
BDD with CucumberBDD with Cucumber
BDD with Cucumber
 
Typescript Fundamentals
Typescript FundamentalsTypescript Fundamentals
Typescript Fundamentals
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
 

Similar to Using Google Test framework for unit testing C++ code

A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)Thierry Gayet
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2Tricode (part of Dept)
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
Unit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonUnit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonSeb Rose
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017Xavi Hidalgo
 
Agile Testing Pasadena JUG Aug2009
Agile Testing Pasadena JUG Aug2009Agile Testing Pasadena JUG Aug2009
Agile Testing Pasadena JUG Aug2009Grig Gheorghiu
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Comunidade NetPonto
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Hong Le Van
 

Similar to Using Google Test framework for unit testing C++ code (20)

A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
The Test way
The Test wayThe Test way
The Test way
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking SkeletonUnit Testing, TDD and the Walking Skeleton
Unit Testing, TDD and the Walking Skeleton
 
Unit Testing and TDD 2017
Unit Testing and TDD 2017Unit Testing and TDD 2017
Unit Testing and TDD 2017
 
Agile Testing Pasadena JUG Aug2009
Agile Testing Pasadena JUG Aug2009Agile Testing Pasadena JUG Aug2009
Agile Testing Pasadena JUG Aug2009
 
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...Testes? Mas isso não aumenta o tempo de projecto? Não quero...
Testes? Mas isso não aumenta o tempo de projecto? Não quero...
 
Test Driven
Test DrivenTest Driven
Test Driven
 
Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++Test driven development and unit testing with examples in C++
Test driven development and unit testing with examples in C++
 

Recently uploaded

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Recently uploaded (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

Using Google Test framework for unit testing C++ code

  • 1. Using the Google unit test framework (aka Google Test) Thierry GAYET
  • 2.
  • 4. Unit Testing definition : “ A unit test is a test of behaviour (normally functional) whose success or failure is wholly determined by the correctness of the test and the correctness of the unit under test. Thus the unit under test has no external dependencies across boundaries of trust or control, which could introduce other sources of failure. Such external dependencies include networks, databases, files, registries, clocks and user interfaces.” What is an unit test ?
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17. Gtest in detail step by step
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24. Death Tests : example 1/2 #include <gtest/gtest.h> // ******** DEATH TESTS ******** void dieWithExitCode(int exitCode, const std::string& msg) { std::cerr << msg; exit(exitCode); } TEST(ExitCodeDeathTest, processShouldExitWithCorrectCode) { EXPECT_EXIT(dieWithExitCode(5, &quot;Fatal error processing request&quot;), ::testing::ExitedWithCode(5), &quot;error&quot;); } TEST(ExitCodeDeathTest, failsWhenProcessExitsWithIncorrectCode) { EXPECT_EXIT(dieWithExitCode(4, &quot;Fatal error processing request&quot;), ::testing::ExitedWithCode(5), &quot;error&quot;); } TEST(ExitCodeDeathTest, failsWhenProcessExitsWithIncorrectMsg) { EXPECT_EXIT(dieWithExitCode(5, &quot;Unable to process request&quot;), ::testing::ExitedWithCode(5), &quot;error&quot;); } // ******** DEATH TESTS FOR NON-ZERO EXIT CODE ******** TEST(ExitCodeDeathTest, processShouldExitWithNonZeroCode) { EXPECT_DEATH(dieWithExitCode(5, &quot;Fatal error processing request&quot;), &quot;error&quot;); } TEST(ExitCodeDeathTest, failsWhenProcessExitsWithCodeZero) { EXPECT_DEATH(dieWithExitCode(0, &quot;Fatal error processing request&quot;), &quot;error&quot;); }
  • 25. Death Tests : example 2/2 TEST(ExitCodeDeathTest, failsWhenProcessExitsWithNonZeroCodeButIncorrectMsg) { EXPECT_DEATH(dieWithExitCode(5, &quot;Unable to process request&quot;), &quot;error&quot;); } // ********* HOME GROWN PREDICATES ******* class ExitCodeRangeCheck { public: ExitCodeRangeCheck(int min_, int max_) : min(min_), max(max_) { } bool operator()(int exitCode) { return (exitCode >= min) && (exitCode <= max); } private: const int min; const int max; }; TEST(ExitCodeDeathTest, processExitCodeShouldBeInRangeNoRegex) { EXPECT_EXIT(dieWithExitCode(5, &quot;Fatal error processing request&quot;), ExitCodeRangeCheck(2,7), &quot;&quot;); } TEST(ExitCodeDeathTest, processExitCodeShouldBeInRangeAnyChars) { EXPECT_EXIT(dieWithExitCode(5, &quot;Fatal error processing request&quot;), ExitCodeRangeCheck(2,7), &quot;.*&quot;); } TEST(ExitCodeDeathTest, processExitCodeShouldBeOutOfRangeAnyChars) { EXPECT_EXIT(dieWithExitCode(1, &quot;Fatal error processing request&quot;), ExitCodeRangeCheck(2,7), &quot;.*&quot;); }
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37. Gtest with language C
  • 38.
  • 39. Architecture of the example Libgm_os gtest gTest_gm_os_posix gtest.pc gtest.so include/ Libgm_os.a include/ Example of a gtest usage. gtest Installation on the stagingdir  pkgconfig compilation link Binary test based on gtest  Library to test 
  • 40.
  • 41.
  • 42. Beginning of the test class /* System header */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* Local header */ #include “gm_os.h&quot; /* Google test header */ #include <gtest/gtest.h> namespace RevolutionS { /** * @brief C++ Class defined for wrapping the unit test */ class GM_OS_TestSuite : public ::testing::Test { protected: GM_OS_TestSuite () { printf( “GM_OS_TestSuite - Constructor&quot; ); g_exit_thread = false; g_exit_main = false; } /* GM_OS_TestSuite */
  • 43. ...end of the test class // You can do clean-up work that doesn't throw exceptions here. virtual ~ GM_OS_TestSuite () { printf( “GM_OS_TestSuite - Destructor&quot; ); } /* ~GM_OS_TestSuite */ // Code here will be called immediately after the constructor (right before each test). virtual void SetUp() { printf(“GM_OS_TestSuite - initialisation of the environment &quot;); /* Launch the GM_OS init function */ } /* SetUp */ // Code here will be called immediately after each test (right before the destructor). virtual void TearDown() { printf(“GM_OS_TestSuite - cleaning the environment &quot; ); } /* TearDown */ };
  • 44. The unitary tests TEST_F( GM_OS_TestSuite , the_unix_pthread_should_start) { EtPl_OS_ThreadId myThread_id; EXPECT_EQ( 0, EtPl_OS_ThreadCreate(myfuncThread, NULL, NULL, 4096, 63, &quot;mon thread&quot;, &myThread_id) ); } TEST_F( GM_OS_TestSuite , give_the_delay_between_two_times ) { GM_OS_Time starttime = 0; GM_OS_Time endtime = 45; GM_OS_Time delayExpected = 45; EXPECT_EQ( delayExpected, GM_OS_TimeCalculateDelay(starttime, endtime) ); } (...) // put other test case here ... (...) } /* Namespace */
  • 45. The main function int main(int argc, char* argv[], char* env[]) { int rcmain = 0; int main_heap_size = 800*1024; /* OOM_DEFAULT_ET_MAIN_HEAP_SIZE : 800ko */ int nb_max_heaps = 48; /* OOM_DEFAULT_ET_NB_MAX_HEAPS */ int et_central_thread_priority = -1; /* */ /* -------------------------------------------- */ /* Set the gtest's context */ /* -------------------------------------------- */ ::testing::GTEST_FLAG(color) = &quot;yes&quot;; ::testing::GTEST_FLAG(print_time) = true; ::testing::GTEST_FLAG(output) = &quot;xml:junit_export.xml&quot;; /* -------------------------------------------- */ /* Initialize and prepare the tests */ /* -------------------------------------------- */ ::testing::InitGoogleTest(&argc, argv); GM_OS_Init( main_heap_size, nb_max_heaps, et_central_thread_priority ); /* -------------------------------------------- */ /* Run all the tests */ /* -------------------------------------------- */ rcmain = RUN_ALL_TESTS(); return rcmain; } /* main */
  • 46. Build $ make g++ -DPACKAGE_NAME=amp;quot;libetpl_oss_posixamp;quot; -DPACKAGE_TARNAME=GM_OSamp;quot; -DPACKAGE_VERSION=amp;quot;1.0.0amp;quot; -DPACKAGE_STRING=GM_OS1.0.0amp;quot; -DPACKAGE_BUGREPORT=amp;quot;thierry.gayet2@technicolor.comamp;quot; -DPACKAGE_URL=amp;quot;amp;quot; -DPACKAGE=GM_OSamp;quot; -DVERSION=amp;quot;1.0.0amp;quot; -DSTDC_HEADERS=1 -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DHAVE_DLFCN_H=1 -DLT_OBJDIR=amp;quot;.libs/amp;quot; -I. -I/local/home/gayetth/bck_revolution/revolution/target/usr/local/include/ -I/local/home/gayetth/bck_revolution/revolution/target/usr/local/include/uno -I../include -I./include -I../src/os -I../include -g -O2 -Wall -O2 -MT gtest_etpl_oss_posix-gtest_unit_os.o -MD -MP -MF .deps/gtest_etpl_oss_posix-gtest_unit_os.Tpo -c -o gtest_etpl_oss_posix-gtest_unit_os.o `test -f 'src/gtest_unit_os.cpp' || echo './'`src/gtest_unit_os.cpp mv -f .deps/gtest_etpl_oss_posix-gtest_unit_os.Tpo .deps/gtest_etpl_oss_posix-gtest_unit_os.Po /bin/bash ../libtool --tag=CXX --mode=link g++ -g -O2 -Wall -O2 ../src/.libs/libetpl_oss_posix.a -o gtest_etpl_oss_posix gtest_etpl_oss_posix-gtest_unit_os.o -L/local/home/gayetth/bck_revolution/revolution/target/usr/local/lib -lgtest -L/local/home/gayetth/bck_revolution/revolution/target/usr/local/lib -luno libtool: link: g++ -g -O2 -Wall -O2 -o gtest_etpl_oss_posix gtest_etpl_oss_posix-gtest_unit_os.o ../src/.libs/libetpl_oss_posix.a -L/local/home/gayetth/bck_revolution/revolution/target/usr/local/lib /local/home/gayetth/gayetth@141.11.146.121/target/usr/local/lib/libgtest.so /local/home/gayetth/gayetth@141.11.146.121/target/usr/local/lib/libuno.so -pthread -Wl,-rpath -Wl,/local/home/gayetth/gayetth@141.11.146.121/target/usr/local/lib -Wl,-rpath -Wl,/local/home/gayetth/gayetth@141.11.146.121/target/usr/local/lib ( … )
  • 47.
  • 48. Junit xml export <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <testsuites tests=&quot;24&quot; failures=&quot;0&quot; disabled=&quot;0&quot; errors=&quot;0&quot; time=&quot;0.001&quot; name=&quot;AllTests&quot;> <testsuite name=&quot;GM_OS_TestSuite&quot; tests=&quot;24&quot; failures=&quot;0&quot; disabled=&quot;0&quot; errors=&quot;0&quot; time=&quot;0.001&quot;> <testcase name=&quot;the_unix_semaphore_should_lock&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;should_wait_for_a_semaphore_with_timeout&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;should_send_a_signal_to_the_semaphore&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;the_unix_semaphore_should_remove_a_semaphore_just_initialized&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;create_a_mutex&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;lock_a_mutex&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;unlock_a_mutex&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;remove_a_mutex&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;add_a_delay_to_a_time&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;give_the_delay_between_two_times&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;get_the_current_posix_time&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;set_then_get_the_current_utc_time&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;datetime_and_string_conversion&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;create_a_new_message_queue&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;remove_a_message_queue&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;create_a_new_heap&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;remove_a_heap&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;allocate_some_memory&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;get_size_free_memory&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;get_size_free_block&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;the_unix_pthread_should_start&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;Increase_an_atomic_variable&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;Decrease_an_atomic_variable&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> <testcase name=&quot;Set_a_variable_not_atomic_yet&quot; status=&quot;run&quot; time=&quot;0&quot; classname=&quot;GM_OS_TestSuite&quot; /> </testsuite> </testsuites> Sample of xml export automatically generated: That can be imported into Hudson as is.
  • 49. configure.ac of this example dnl Brief : configure for my Package dnl Team : Revolution-S - Rennes AC_PREREQ(2.59) m4_define([my_package_major_version], [1]) m4_define([my_package_minor_version], [0]) m4_define([my_package_micro_version], [0]) m4_define([my_package_version], [my_package_major_version. my_package_minor_version. my_package_micro_version]) AC_INIT([my_package], [my_package_version], [thierry.gayet2@technicolor.com]) (...) AC_ARG_ENABLE(test, AS_HELP_STRING([--enable-test], [Enable the test unitary support [default=no]]), [case &quot;${enableval}&quot; in yes) have_test=true ;; no) have_test=false ;; *) AC_MSG_ERROR(bad value ${enableval} for --enable-test) ;; esac], [have_test=false]) AM_CONDITIONAL(HAVE_TEST, $have_test) AC_MSG_CHECKING(Checking the test support) if test &quot;$have_test&quot; != &quot;false&quot; ; then AC_MSG_RESULT([yes]) PKG_CHECK_MODULES([GTEST],[gtest],[have_libgtest=yes],[have_libgtest=no]) if test &quot;$have_libgtest&quot; = no ; then AC_MSG_ERROR([Missing libgtest library (http://code.google.com/p/googletest/) !!]) fi Else AC_MSG_RESULT([no]) fi (...) AC_OUTPUT(unit_test/Makefile)
  • 50. Makefile.am of this example # # Makefile for the unit test based on Google Test framework # (...) if HAVE_TEST TESTS = gmos_gtest else TESTS = endif noinst_PROGRAMS = $(TESTS) gmos_gtest _SOURCES = $(top_srcdir)/unit_test/src/test_gm_os.cpp gmos_gtest _CPPFLAGS = -I$(HEADER_DIR) $(GTEST_CFLAGS) gmos_gtest _LDFLAGS = $(top_srcdir)/.libs/libgm_os.a -lpthread gmos_gtest _LDADD = $(GTEST_LIBS) # # END OF FILE #
  • 51. Gtest with language C++
  • 52.
  • 53.
  • 54. Predicate Assertions for Better Error Messages Even though Google Test has a rich set of assertions, they can never be complete, as it's impossible (nor a good idea) to anticipate all the scenarios a user might run into. Therefore, sometimes a user has to use EXPECT_TRUE() to check a complex expression, for lack of a better macro. This has the problem of not showing you the values of the parts of the expression, making it hard to understand what went wrong. As a workaround, some users choose to construct the failure message by themselves, streaming it into EXPECT_TRUE(). However, this is awkward especially when the expression has side-effects or is expensive to evaluate.
  • 55. #include <gtest/gtest.h> class MyException : public std::exception { public: MyException(const char* message) : std::exception(message) {} }; void methodThatThrows() { throw MyException(&quot;Exception&quot;); } void methodThatDoesNotThrow() { } TEST(ExceptionTest, ensureSpecificExceptionIsThrown) { EXPECT_THROW(methodThatThrows(), MyException); } TEST(ExceptionTest, ensureExceptionThrownHasExectedBaseClass) { EXPECT_THROW(methodThatThrows(), std::exception); } TEST(ExceptionTest, ensureSomeExceptionIsThrown) { EXPECT_ANY_THROW(methodThatThrows()); } TEST(ExceptionTest, ensureNoExceptionIsThrown) { EXPECT_NO_THROW(methodThatDoesNotThrow()); } Predicate Assertions for Better Error Messages Example 1
  • 56. Predicate Assertions for Better Error Messages Example 2 – 1/2 #include <gtest/gtest.h> void method1() {} void method2() {} void method3() {} TEST(StructuringTests, canUseCompoundStatementsInThrowAssertions) { ASSERT_NO_THROW( method1(); method2(); method3(); ); } //********** SCOPED TRACE *********** void checkRange(int min, int max, int actual) { ASSERT_LE(min, actual) << &quot;Actual is less than minimum&quot;; ASSERT_GE(max, actual) << &quot;Actual is greater than maximum&quot;; } void checkAgeEligibility(int age) { SCOPED_TRACE(&quot;Age eligibility&quot;); checkRange(25, 39, age); } void checkIncomeEligibility(int salary) { SCOPED_TRACE(&quot;Salary eligibility&quot;); checkRange(20, 45, salary); }
  • 57. Predicate Assertions for Better Error Messages Example 2 – 2/2 void promotionEligibilityTest(int salary, int age) { checkAgeEligibility(age); checkIncomeEligibility(salary); } TEST(StructuringTests, checkIsEligibleForMarketingPromotion) { promotionEligibilityTest(30, 22); } // ********** FATAL FAILURES **************** TEST(StructuringTests, checksAllEligibilityCriteriaEvenAfterFailure) { checkAgeEligibility(2); checkIncomeEligibility(2); } TEST(StructuringTests, onlyChecksEligibilityCriteriaIfNoFailure_1) { ASSERT_NO_FATAL_FAILURE(checkAgeEligibility(2)); ASSERT_NO_FATAL_FAILURE(checkIncomeEligibility(2)); } TEST(StructuringTests, onlyChecksEligibilityCriteriaIfNoFailure_2) { checkAgeEligibility(2); if (!HasFatalFailure()) { checkIncomeEligibility(2); } // Also available: // - HasNonfatalFailure // - HasFailure (fatal or non-fatal) }
  • 58.
  • 59. Using a Function That Returns an AssertionResult 1/3 While EXPECT_PRED*() and friends are handy for a quick job, the syntax is not satisfactory: you have to use different macros for different arities, and it feels more like Lisp than C++. The ::testing::AssertionResult class solves this problem. An AssertionResult object represents the result of an assertion (whether it's a success or a failure, and an associated message). You can create an AssertionResult using one of these factory functions: namespace testing { // Returns an AssertionResult object to indicate that an assertion has // succeeded. AssertionResult AssertionSuccess(); // Returns an AssertionResult object to indicate that an assertion has failed. AssertionResult AssertionFailure(); } You can then use the << operator to stream messages to the AssertionResult object.
  • 60. Using a Function That Returns an AssertionResult 2/3 To provide more readable messages in Boolean assertions (e.g. EXPECT_TRUE()), write a predicate function that returns AssertionResult instead of bool. For example, if you define IsEven() as: ::testing::AssertionResult IsEven(int n) {   if ((n % 2) == 0)     return ::testing::AssertionSuccess();   else     return ::testing::AssertionFailure() << n << &quot; is odd&quot;; } Instead of: bool IsEven(int n) {   return (n % 2) == 0; } The failed assertion EXPECT_TRUE(IsEven(Fib(4))) will print: Value of: IsEven(Fib(4)) Actual: false (3 is odd) Expected: true
  • 61.
  • 62. Using a Predicate-Formatter 1/3 If you find the default message generated by (ASSERT|EXPECT)_PRED* and (ASSERT|EXPECT)_(TRUE|FALSE) unsatisfactory, or some arguments to your predicate do not support streaming to ostream, you can instead use the following predicate-formatter assertions to fully customize how the message is formatted: The difference between this and the previous two groups of macros is that instead of a predicate, (ASSERT|EXPECT)_PRED_FORMAT* take a predicate-formatter (pred_formatn), which is a function or functor with the signature: ::testing::AssertionResult PredicateFormattern(const char* expr1, const char* expr2, ... const char* exprn, T1 val1, T2 val2, ... Tn valn); where val1, val2, ..., and valn are the values of the predicate arguments, and expr1, expr2, ..., and exprn are the corresponding expressions as they appear in the source code. The types T1, T2, ..., and Tn can be either value types or reference types. For example, if an argument has type Foo, you can declare it as either Foo or const Foo&, whichever is appropriate. Fatal assertion Nonfatal assertion Verifies ASSERT_PRED_FORMAT1(pred_format1, val1); EXPECT_PRED_FORMAT1(pred_format1, val1`); pred_format1(val1) is successful ASSERT_PRED_FORMAT2(pred_format2, val1, val2); EXPECT_PRED_FORMAT2(pred_format2, val1, val2); pred_format2(val1, val2) is successful
  • 63. Using a Predicate-Formatter 2/3 A predicate-formatter returns a ::testing::AssertionResult object to indicate whether the assertion has succeeded or not. The only way to create such an object is to call one of these factory functions: As an example, let's improve the failure message in the previous example, which uses EXPECT_PRED2(): // Returns the smallest prime common divisor of m and n, // or 1 when m and n are mutually prime. int SmallestPrimeCommonDivisor(int m, int n) { ... } // A predicate-formatter for asserting that two integers are mutually prime. ::testing::AssertionResult AssertMutuallyPrime(const char* m_expr,                                                 const char* n_expr,                                                 int m,                                                 int n) {   if (MutuallyPrime(m, n))     return ::testing::AssertionSuccess();     return ::testing::AssertionFailure()       << m_expr << &quot; and &quot; << n_expr << &quot; (&quot; << m << &quot; and &quot; << n       << &quot;) are not mutually prime, &quot; << &quot;as they have a common divisor &quot;       << SmallestPrimeCommonDivisor(m, n); } With this predicate-formatter, we can use: EXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);
  • 64.
  • 65. Using a Predicate-Formatter : example 1/2 static const int SALARY(20000); static const int MORTGAGE(100000); const int GENEROUS_MULTIPLIER(5); const int STANDARD_MULTIPLIER(4); // ********** EXPLICIT EXPECTATION *********** TEST(ExpectationFailureTests, canTestExplicitlyForResult) { EXPECT_TRUE(earnsEnoughToAffordMortgage(SALARY, MORTGAGE, GENEROUS_MULTIPLIER)); //EXPECT_FALSE(earnsEnoughToAffordMortgage(SALARY, MORTGAGE, STANDARD_MULTIPLIER)); EXPECT_TRUE(earnsEnoughToAffordMortgage(SALARY, MORTGAGE, STANDARD_MULTIPLIER)) << &quot;Fails affordability test&quot;; } // ********** PREDICATED EXPECTATION *********** TEST(ExpectationFailureTests, canImproveTestsTernaryPredicate) { EXPECT_PRED3(earnsEnoughToAffordMortgage, SALARY, MORTGAGE, STANDARD_MULTIPLIER); } // ********** FORMATTED PREDICATE *********** ::testing::AssertionResult checkAffordability( const char* salary_text, const char* mortgage_text, const char* multiplier_text, int salary, int mortgage, int multiplier) { int maxLoanAmount = salary * multiplier; if (maxLoanAmount >= mortgage) { return ::testing::AssertionSuccess(); } else {
  • 66.
  • 67.
  • 68.
  • 69.
  • 70. TEST(FloatingPoint, shouldTestToAcceptablePrecision) { double d1 = 1.0 / 999999999.99999999999; double d2 = 1.0 / 999999999.999999; EXPECT_EQ(d1, d2); EXPECT_DOUBLE_EQ(d1, d2); EXPECT_NEAR(d1, d2, 0.000001); } Floating-Point Predicate-Format Functions¶
  • 71.
  • 72.
  • 73. Assertion Placement You can use assertions in any C++ function. In particular, it doesn't have to be a method of the test fixture class. The one constraint is that assertions that generate a fatal failure (FAIL* and ASSERT_*) can only be used in void-returning functions. This is a consequence of Google Test not using exceptions. By placing it in a non-void function you'll get a confusing compile error like &quot;error: void value not ignored as it ought to be&quot;. If you need to use assertions in a function that returns non-void, one option is to make the function return the value in an out parameter instead. For example, you can rewrite T2 Foo(T1 x) to void Foo(T1 x, T2* result). You need to make sure that *result contains some sensible value even when the function returns prematurely. As the function now returns void, you can use any assertion inside of it. If changing the function's type is not an option, you should just use assertions that generate non-fatal failures, such as ADD_FAILURE* and EXPECT_*. Note: Constructors and destructors are not considered void-returning functions, according to the C++ language specification, and so you may not use fatal assertions in them. You'll get a compilation error if you try. A simple workaround is to transfer the entire body of the constructor or destructor to a private void-returning method. However, you should be aware that a fatal assertion failure in a constructor does not terminate the current test, as your intuition might suggest; it merely returns from the constructor early, possibly leaving your object in a partially-constructed state. Likewise, a fatal assertion failure in a destructor may leave your object in a partially-destructed state. Use assertions carefully in these situations!
  • 74. Teaching Google Test How to Print Your Values When a test assertion such as EXPECT_EQ fails, Google Test prints the argument values to help you debug. It does this using a user-extensible value printer. This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the << operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out. As mentioned earlier, the printer is  extensible . That means you can teach it to do a better job at printing your particular type than to dump the bytes. To do that, define << for your type: #include <iostream> namespace foo { class Bar { ... };  // We want Google Test to be able to print instances of this. // It's important that the << operator is defined in the SAME // namespace that defines Bar.  C++'s look-up rules rely on that. ::std::ostream& operator<<(::std::ostream& os, const Bar& bar) {   return os << bar.DebugString();  // whatever needed to print bar to os } }  // namespace foo Sometimes, this might not be an option: your team may consider it bad style to have a << operator for Bar, or Bar may already have a << operator that doesn't do what you want (and you cannot change it). If so, you can instead define a PrintTo() function like this:
  • 75. Teaching Google Test How to Print Your Values #include <iostream> namespace foo { class Bar { ... }; // It's important that PrintTo() is defined in the SAME // namespace that defines Bar.  C++'s look-up rules rely on that. void PrintTo(const Bar& bar, ::std::ostream* os) {   *os << bar.DebugString();  // whatever needed to print bar to os } }  // namespace foo If you have defined both << and PrintTo(), the latter will be used when Google Test is concerned. This allows you to customize how the value appears in Google Test's output without affecting code that relies on the behavior of its << operator. If you want to print a value x using Google Test's value printer yourself, just call ::testing::PrintToString( x ), which returns anstd::string: vector<pair<Bar, int> > bar_ints = GetBarIntVector(); EXPECT_TRUE(IsCorrectBarIntVector(bar_ints))     << &quot;bar_ints = &quot; << ::testing::PrintToString(bar_ints);
  • 76.
  • 77. How to Write a Death Test Note : We use the word &quot;crash&quot; here to mean that the process terminates with a non-zero exit status code. There are two possibilities: either the process has called exit() or _exit() with a non-zero value, or it may be killed by a signal. This means that if statement terminates the process with a 0 exit code, it is not considered a crash by EXPECT_DEATH. Use EXPECT_EXIT instead if this is the case, or if you want to restrict the exit code more precisely. A predicate here must accept an int and return a bool. The death test succeeds only if the predicate returns true. Google Test defines a few predicates that handle the most common cases: This expression is true if the program exited normally with the given exit code. ::testing::ExitedWithCode(exit_code) ::testing::KilledBySignal(signal_number)  // Not available on Windows. This expression is true if the program was killed by the given signal. The *_DEATH macros are convenient wrappers for *_EXIT that use a predicate that verifies the process' exit code is non-zero.
  • 78. How to Write a Death Test Note that a death test only cares about three things: 1. does statement abort or exit the process? 2. (in the case of ASSERT_EXIT and EXPECT_EXIT) does the exit status satisfy predicate? Or (in the case of ASSERT_DEATH and EXPECT_DEATH) is the exit status non-zero? And 3. does the stderr output match regex? In particular, if statement generates an ASSERT_* or EXPECT_* failure, it will not cause the death test to fail, as Google Test assertions don't abort the process. To write a death test, simply use one of the above macros inside your test function. For example, TEST(My*DeathTest*, Foo) {   // This death test uses a compound statement.   ASSERT_DEATH({ int n = 5; Foo(&n); }, &quot;Error on line .* of Foo()&quot;); } TEST(MyDeathTest, NormalExit) {   EXPECT_EXIT(NormalExit(), ::testing::ExitedWithCode(0), &quot;Success&quot;); } TEST(MyDeathTest, KillMyself) {   EXPECT_EXIT(KillMyself(), ::testing::KilledBySignal(SIGKILL), &quot;Sending myself unblockable signal&quot;); }
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86. Using Assertions in Sub-routines Without the trace, it would've been difficult to know which invocation of Sub1() the two failures come from respectively. (You could add an extra message to each assertion in Sub1() to indicate the value of n, but that's tedious.) Some tips on using SCOPED_TRACE: With a suitable message, it's often enough to use SCOPED_TRACE at the beginning of a sub-routine, instead of at each call site. When calling sub-routines inside a loop, make the loop iterator part of the message in SCOPED_TRACE such that you can know which iteration the failure is from. Sometimes the line number of the trace point is enough for identifying the particular invocation of a sub-routine. In this case, you don't have to choose a unique message for SCOPED_TRACE. You can simply use &quot;&quot;. You can use SCOPED_TRACE in an inner scope when there is one in the outer scope. In this case, all active trace points will be included in the failure messages, in reverse order they are encountered. The trace dump is clickable in Emacs' compilation buffer - hit return on a line number and you'll be taken to that line in the source file! Availability:  Linux, Windows, Mac.
  • 87.
  • 88. Asserting on Subroutines As shown above, if your test calls a subroutine that has an  ASSERT_*  failure in it, the test will continue after the subroutine returns. This may not be what you want. Often people want fatal failures to propagate like exceptions. For that Google Test offers the following macros: Only failures in the thread that executes the assertion are checked to determine the result of this type of assertions. If  statement  creates new threads, failures in these threads are ignored. Examples: ASSERT_NO_FATAL_FAILURE(Foo()); int i; EXPECT_NO_FATAL_FAILURE({   i = Bar(); }); Availability:  Linux, Windows, Mac. Assertions from multiple threads are currently not supported. Fatal assertion Nonfatal assertion Verifies ASSERT_NO_FATAL_FAILURE( statement ); EXPECT_NO_FATAL_FAILURE( statement ); statement  doesn't generate any new fatal failures in the current thread.
  • 89. Checking for Failures in the Current Test HasFatalFailure() in the ::testing::Test class returns true if an assertion in the current test has suffered a fatal failure. This allows functions to catch fatal failures in a sub-routine and return early. class Test {  public:   ...   static bool HasFatalFailure(); }; The typical usage, which basically simulates the behavior of a thrown exception, is: TEST(FooTest, Bar) {   Subroutine();   // Aborts if Subroutine() had a fatal failure.   if (HasFatalFailure())     return;   // The following won't be executed.   ... } If HasFatalFailure() is used outside of TEST() , TEST_F() , or a test fixture, you must add the ::testing::Test:: prefix, as in: if (::testing::Test::HasFatalFailure())   return; Similarly, HasNonfatalFailure() returns true if the current test has at least one non-fatal failure, and HasFailure() returns true if the current test has at least one failure of either kind. Availability:  Linux, Windows, Mac. HasNonfatalFailure() and HasFailure() are available since version 1.4.0.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99. How to Write Value-Parameterized Tests Finally, you can use  INSTANTIATE_TEST_CASE_P  to instantiate the test case with any set of parameters you want. Google Test defines a number of functions for generating test parameters. They return what we call (surprise!)  parameter generators . Here is a summary of them, which are all in the testing  namespace: For more details, see the comments at the definitions of these functions in the source code. The following statement will instantiate tests from the  FooTest  test case each with parameter values  &quot;meeny&quot; ,  &quot;miny&quot; , and  &quot;moe&quot; . INSTANTIATE_TEST_CASE_P(InstantiationName,                         FooTest,                         ::testing::Values(&quot;meeny&quot;, &quot;miny&quot;, &quot;moe&quot;)); o distinguish different instances of the pattern (yes, you can instantiate it more than once), the first argument to INSTANTIATE_TEST_CASE_P is a prefix that will be added to the actual test case name. Remember to pick unique prefixes for different instantiations. The tests from the instantiation above will have these names: Range(begin, end[, step]) Yields values  {begin, begin+step, begin+step+step, ...} . The values do not include  end .  step  defaults to 1. Values(v1, v2, ..., vN) Yields values  {v1, v2, ..., vN} . ValuesIn(container) and  ValuesIn(begin, end) Yields values from a C-style array, an STL-style container, or an iterator range  [begin, end) . Bool() Yields sequence  {false, true} . Combine(g1, g2, ..., gN) Yields all combinations (the Cartesian product for the math savvy) of the values generated by the  N  generators. This is only available if your system provides the  <tr1/tuple> header. If you are sure your system does, and Google Test disagrees, you can override it by defining  GTEST_HAS_TR1_TUPLE=1 . See comments in  include/gtest/internal/gtest-port.h  for more information.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104. TYPED TESTS : example 1/2 #include <gtest/gtest.h> template <typename T> class TypedTests : public ::testing::Test { protected: T t; T t2; }; class MyClass { public: operator int() { throw &quot;Do not convert MyClass to int&quot;; } }; typedef ::testing::Types<char, int, unsigned int, bool, MyClass> TypesToTest; TYPED_TEST_CASE(TypedTests, TypesToTest); TYPED_TEST(TypedTests, implicitlyConvertibleToInt) { EXPECT_NO_THROW(int i = this->t); }
  • 105. TYPED TESTS : example 2/2 TYPED_TEST(TypedTests, operatorStarIsSymmetric) { EXPECT_NO_THROW( EXPECT_EQ(t*t2, t2*t) ); } // Inside a test, refer to the special name TypeParam to get the type // parameter. Since we are inside a derived class template, C++ requires // us to visit the members of FooTest via 'this'. //e.g. TypeParam n = this->value_; // To visit static members of the fixture, add the 'TestFixture::' // prefix. // e.g. n += TestFixture::shared_; // To refer to typedefs in the fixture, add the 'typename TestFixture::' // prefix. The 'typename' is required to satisfy the compiler. // typename TestFixture::List values; // values.push_back(n);
  • 106.