49

I'm programming some unit test with the Google test framework. But I want to check whether some asserts are well placed and are useful. Is there a way to catch an assert in Google test?

Example code under test:

int factorial(int n){
    assert(n >= 0);
    //....
}

And then the test:

#include <gtest/gtest.h>
TEST(FactorialTest,assertNegative){
    EXPECT_ANY_THROW({
         factorial(-1);
    });
}

But EXPECT_ANY_THROW doesn't catch the assert but only exceptions. I'm searching for a solution to catch asserts.

Keith Pinson
  • 7,835
  • 7
  • 61
  • 104
Killrazor
  • 6,856
  • 15
  • 53
  • 69

2 Answers2

42

Google test provides ASSERT_DEATH, EXPECT_DEATH and other related macros.

This question and What are Google Test, Death Tests are each other's answers. Does that make them duplicates, or not? ;-)

1ace
  • 5,272
  • 4
  • 23
  • 30
Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • 3
    Duplicate answers do not necessary constitute duplicate questions. However, your answer is essentially just a link---which is discouraged. – Keith Pinson Feb 06 '13 at 22:54
  • 2
    I have mentioned the names of the most relevant macros, so that if the link breaks then a reader has a basis to find up to date documentation. – Steve Jessop Sep 04 '14 at 09:52
  • 2
    Moved here: https://google.github.io/googletest/advanced.html#death-tests – Silicomancer Jun 05 '21 at 21:09
2

EXPECT_FATAL_FAILURE(statement,text) and EXPECT_NONFATAL_FAILURE(statement,text) will only pass if 'statement' invokes a failing ASSERT_x or EXECT_x respectively.

These statements will pass in your tests:

EXPECT_NONFATAL_FAILURE( EXPECT_TRUE( 0 ), "" ); EXPECT_FATAL_FAILURE( ASSERT_TRUE( 0 ), "" );

Michael
  • 2,118
  • 1
  • 19
  • 25
  • 1
    These statements are not available. I get `error: ‘EXPECT_FATAL_FAILURE’ was not declared in this scope; did you mean ‘EXPECT_NO_FATAL_FAILURE’?` and `error: macro "EXPECT_NO_FATAL_FAILURE" passed 2 arguments, but takes just 1`. How do you get them? – Ingo Dec 06 '22 at 20:46