How to catch an assert with Google test?

北城余情 提交于 2019-12-05 08:27:29

问题


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.


回答1:


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




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



来源:https://stackoverflow.com/questions/3756422/how-to-catch-an-assert-with-google-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!