Search code examples
c++unit-testinggoogletest

How to use a return value from a gtest to another test


I am trying to test a C++ program via Google test framework.

My code:

int addNumbers(int a, int b)
{
    return a + b;
}

int subtractNumbers(int a, int b)
{
    return a - b;
}

Unit test Code:

//first test
TEST(testMath, addTest1)
{
    EXPECT_EQ(37, addNumbers(14, 23));
    getchar();
}

//second test
TEST(testMath, subtractTest1)
{
    EXPECT_EQ(25, subtractNumbers(37, 12));
    getchar();
}

//third test
TEST(testMath, addTest2)
{
    EXPECT_EQ(62, addNumbers(37, 25));
    getchar();
}

But, I need my unit test to be in a different way.

My Expectation: I need to get the return value (result) of the first test and use it in the second test as dynamic (If the first test is failed, then the program should terminate showing error details). When the first test and the second test are OK (not failed), then the return values from the first and second test should be parameterized to the third test.

Desired Algorithm (as help from you):

Step 1: Run first test addNumbers(14, 23);

Step 2: Check the expected and return values(A);

Step 3.1: If test failed, terminate the program showing Error details;

Step 3.2: If OK (not failed), Run the second test subtractNumbers(A, 12);

Step 4: Check the expected and return values(B);

Step 5.1: If test failed, terminate the program showing OK details and Error details;

Step 5.2: If OK (not failed), Run the third test addNumbers(A,B);

Step 6: Check the expected and return values;

Step 7.1: If test failed, terminate the program showing OK details and Error details;

Step 7.2: If OK, show the OK details.


Solution

  • Using the various ASSERT_* macros will cause a test to abort on failure. You can convert the EXPECT_EQ to ASSERT_EQ, then place them all within the same TEST().

    TEST(testMath, testAll)
    {
      auto A = addNumbers(14, 23);
      ASSERT_EQ(37, A);
      auto B = subtractNumbers(A, 12)
      ASSERT_EQ(25, B);
      ASSERT_EQ(62, addNumbers(A, B));
    }