How to catch an assert with Google test?
Asked Answered
M

2

51

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.

Marras answered 21/9, 2010 at 0:2 Comment(0)
S
43

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? ;-)

Sachsen answered 21/9, 2010 at 0:6 Comment(3)
Duplicate answers do not necessary constitute duplicate questions. However, your answer is essentially just a link---which is discouraged.Oxfordshire
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.Sachsen
Moved here: google.github.io/googletest/advanced.html#death-testsCephalonia
D
3

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 ), "" );

Ditheism answered 18/11, 2019 at 17:48 Comment(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?Punkah

© 2022 - 2024 — McMap. All rights reserved.