Skip to content

Instantly share code, notes, and snippets.

@isc30
Last active Oct 14, 2017
Embed
What would you like to do?
Notes: GUnit

Google Test - Unit

Disabling a Test

Add DISABLED_ prefix to test name

Floating point comparisons

Use EXPECT_FLOAT_EQ

Running the tests

main.cpp

#include <gtest/gtest.h>

int main(int argc, char* argv[])
{
    testing::InitGoogleTest(&argc, argv);

    return RUN_ALL_TESTS();
}

Test types

Basic test

Simplest type of test, declare it on any .CPP file and that's all

TEST(GroupName, TestName)
{
    EXPECT_EQ(1, 1);
    ASSERT_EQ(1, 1);
}

Fixture

Test with base class (allocation before running + deallocation after running, etc)

class MyFixture
    : public testing::Test
{
public:
    MyFixture()
        : Test()
    {
        // Allocation point n.1
        // when Fixture is created
    }
    
    ~MyFixture()
    {
        // Deallocation point n.1
        // when Fixture is destroyed
    }
    
    void SetUp() override
    {
        // Allocation point n.2
        // just before running each test
    }
    
    void TearDown() override
    {
        // Deallocation point n.2
        // just after running each test
    }
};

// Usage
TEST_F(MyFixture, TestName)
{
    // this == MyFixture*
}

Parametrized

Declare a set of test cases, generic fixture to test them all
Func to be tested: int Utils::sum(int, int)

// Declare data structure for storing each test case
struct SumTestCase
{
    int left;
    int right;
    int expectedResult;
};

// Declare parametrized fixture
class SumTest
    : public testing::Test
    , public testing::WithParamInterface<SumTestCase>
{
    // No need for extra implementation (in this case)
}

// Declare generic test using the parameters
TEST_P(SumTest, CheckSumResult)
{
    const auto& tcase = GetParam(); // retrieve current test case
    
    // non-critical assertion
    EXPECT_EQ(Utils::sum(tcase.left, tcase.right), tcase.expectedResult);
}

// Run tests using sets of parameters

INSTANTIATE_TEST_CASE_P(OnlyPositives, SumTest, testing::Values(
    SumTestCase{ 2, 100, 102 },
    SumTestCase{ 15, 15, 30 },
    SumTestCase{ 30, 12, 42 },
    SumTestCase{ 2, 0, 2 },
    SumTestCase{ 0, 2, 2 }
));

INSTANTIATE_TEST_CASE_P(OnlyNegatives, SumTest, testing::Values(
    SumTestCase{ -2, -100, -102 },
    SumTestCase{ -15, -15, -30 },
    SumTestCase{ -30, -12, -42 },
    SumTestCase{ -2, 0, -2 },
    SumTestCase{ 0, -2, -2 }
));

INSTANTIATE_TEST_CASE_P(PositiveNegativeMix, SumTest, testing::Values(
    SumTestCase{ 0, 0, 0 },
    SumTestCase{ -2, 100, 98 },
    SumTestCase{ 15, -15, 0 },
    SumTestCase{ -30, 12, -18 },
    SumTestCase{ -2, 1, -1 },
    SumTestCase{ 1, -2, -1 }
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment