GoogleTest - Death Tests



Death tests in GoogleTest are used to verify that a program terminates in the expected way under certain conditions to ensure consistency. This type of assertion checks if a proper error message is displayed in case of wrong input to a routine or if the process exits with a proper exit code.

How to Write Death Tests?

You can write death tests in GoogleTest using the following assertions −

  • EXPECT_DEATH() or ASSERT_DEATH() − It accepts two parameters a statement and a matcher. This assertion tests if the statement causes the process to terminate with a nonzero exit status and produces stderr output that matches matcher.
  • EXPECT_DEATH_IF_SUPPORTED() or ASSERT_DEATH_IF_SUPPORTED() − It first checks whether death tests are supported or not. If so behaves the same as EXPECT_DEATH.
  • EXPECT_DEBUG_DEATH() or ASSERT_DEBUG_DEATH() − It also behaves the same as EXPECT_DEATH but, in debug mode. When not in debug mode only the statement executed.
  • EXPECT_EXIT() or ASSERT_EXIT() − It takes three parameters a statement, a predicate and a matcher. It verifies that statement causes the process to terminate with an exit status that satisfies predicate, and produces stderr output that matches matcher. Here, the parameter predicate is a function that accepts an integer exit status and returns a boolean value.

Example

The following example illustrates how to write death tests in GoogleTest.

#include <gtest/gtest.h>
#include <iostream>

int divideNum(int numerator, int denominator) {
  if (denominator == 0) {
    std::cerr << "Error Occured: Denominator should not be zero" << std::endl;
    exit(1); 
  }
  return numerator / denominator;
}

TEST(CheckDivison, ForZeroDenominator) {
  // death test
  ASSERT_DEATH(divideNum(25, 0), "Cannot be divided by zero");
}

TEST(CheckDivison, WithZeroDenominator) {
  // death test
  ASSERT_EXIT(divideNum(74, 0), ::testing::ExitedWithCode(1), "Cannot be divided by zero");
}

When you run this code, following output will be displayed on console −

Test project D:/gTest/test5/build
    Start 1: CheckDivison.ForZeroDenominator
1/2 Test #1: CheckDivison.ForZeroDenominator ....***Failed    0.06 sec
    Start 2: CheckDivison.WithZeroDenominator
2/2 Test #2: CheckDivison.WithZeroDenominator ...***Failed    0.03 sec

0% tests passed, 2 tests failed out of 2

Total Test time (real) =   0.19 sec

The following tests FAILED:
          1 - CheckDivison.ForZeroDenominator (Failed)
          2 - CheckDivison.WithZeroDenominator (Failed)
Advertisements