Simple Tests and Test Fixtures
Tests are used to assess the functionality and integrity of our code. They contain various GoogleTest assertions and any valid C++ statements that you choose to include. Tests pass if and only if they run without crashing and all included assertions pass.
Writing Tests
A simple test has the following structure:
#include "gtest/gtest.h"
TEST(TestSuiteName, TestName) {
// ... test body ...
}
An implementation of this can look like this:
#include "gtest/gtest.h"
// all tests are named "ExampleTestOne" or "ExampleTestTwo"
// but they are in different test suites
// these tests are in test suite one
TEST(ExampleSuiteOne, ExampleTestOne) {
EXPECT_STREQ("hello world!", "hello world!");
}
TEST(ExampleSuiteOne, ExampleTestTwo) {
EXPECT_EQ(3 * 3, 9);
}
// these tests are in test suite two
TEST(ExampleSuiteTwo, ExampleTestOne) {
EXPECT_STRNE("foo", "bar");
}
TEST(ExampleSuiteTwo, ExampleTestTwo) {
EXPECT_NE(4 * 4, 15);
}
Writing Test Fixtures
Test fixtures expand upon basic tests. Imagine we want to run multiple tests on the same set of data. Instead of hard-coding the setup and teardown of data for each test, we can use a test fixture to do this in a DRY fashion.
A test using a test fixture has the following structure:
#include "gtest/gtest.h"
TEST_F(TestFixtureClassName, TestName) {
// ... test body ...
}
Suppose we want to test a hypothetical class, MyClass, using a test fixture. The implementation may be as follows.
First, we write our class:
Then, we write our test: