🔍

Overview of GoogleTest Framework

Apr 23, 2025

GoogleTest Primer

Introduction: Why GoogleTest?

  • GoogleTest is a C++ testing framework.
  • Designed to meet Google's specific requirements for testing.
  • Supports multiple platforms: Linux, Windows, Mac.
  • Key beliefs about good tests:
    1. Independent and repeatable: Tests should be isolated.
    2. Organized: Tests should reflect the structure of the code.
    3. Portable and reusable: Platform-neutral.
    4. Informative: Provide detailed failure information.
    5. Focused on content: Minimize housekeeping tasks.
    6. Fast: Efficient use of resources.
  • Based on xUnit architecture.

Beware of the Nomenclature

  • Historical terminology in GoogleTest can be confusing:
    • "Test Case" now referred to as "Test Suite."
    • "Test" refers to what ISTQB calls "Test Case."
  • API transition from TestCase to TestSuite.

Basic Concepts

  • Assertions: Core statements that check conditions.
    • Outcome: Success, nonfatal failure, or fatal failure.
    • Fatal failures abort the current function.
  • Tests: Built using assertions to verify code behavior.
  • Test Suite: Group of tests reflecting code structure.
  • Test Program: Can contain multiple test suites.

Assertions

  • GoogleTest assertions are macros similar to function calls.
  • Two versions:
    • ASSERT_*: Causes fatal failure, aborts the current function.
    • EXPECT_*: Causes nonfatal failure, allows function continuation.
  • Custom failure messages can be provided using the << operator.
  • Supports various assertions: value comparison, string checks, etc.

Simple Tests

  • Defined using TEST() macro:
    • Structure: TEST(TestSuiteName, TestName) { ... }
    • Tests run independently.
  • Example:
    • Factorial function tests using TEST().

Test Fixtures

  • Used for tests sharing similar data/configurations:
    1. Derive a class from testing::Test.
    2. Declare objects in the class.
    3. Use SetUp() for pre-test configuration.
    4. Use TearDown() for post-test cleanup.
  • Use TEST_F() to create tests with fixtures.

Invoking the Tests

  • Tests registered automatically with GoogleTest.
  • Run all tests with RUN_ALL_TESTS().
  • Returns 0 if successful, 1 otherwise.

Writing the main() Function

  • Typically not necessary to write custom main().
  • Use InitGoogleTest() and RUN_ALL_TESTS() for custom setup.
  • GoogleTest provides a default main() implementation.

Known Limitations

  • Thread-safety depends on availability of pthreads library.
  • Not thread-safe on some systems (e.g., Windows).