C++ 如何使用 Google 测试捕获断言?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3756422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:37:59  来源:igfitidea点击:

How to catch an assert with Google test?

c++unit-testinggoogletestassertions

提问by Killrazor

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?

我正在使用 Google 测试框架编写一些单元测试。但我想检查一些断言是否放置得当并且有用。有没有办法在 Google 测试中捕获断言?

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_THROWdoesn't catch the assert but only exceptions. I'm searching for a solution to catch asserts.

EXPECT_ANY_THROW不会捕获断言,而只会捕获异常。我正在寻找捕获断言的解决方案。

采纳答案by Steve Jessop

Google test provides ASSERT_DEATH, EXPECT_DEATHand other related macros.

谷歌测试提供ASSERT_DEATHEXPECT_DEATH等相关宏

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

这个问题和什么是谷歌测试,死亡测试是对方的答案。这是否使它们重复?;-)

回答by Michael

EXPECT_FATAL_FAILURE(statement,text) and EXPECT_NONFATAL_FAILURE(statement,text) will only passif 'statement' invokes a failingASSERT_x or EXECT_x respectively.

EXPECT_FATAL_FAILURE(statement,text) 和 EXPECT_NONFATAL_FAILURE(statement,text)只有在 'statement' 分别调用失败的ASSERT_x 或 EXECT_x时才会通过

These statements will pass in your tests:

这些语句将通过您的测试:

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

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