C++ 在 GoogleTest 中使用 ASSERT 和 EXPECT
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2565299/
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
Using ASSERT and EXPECT in GoogleTest
提问by martjno
While ASSERT_* macros cause termination of test case, EXPECT_* macros continue its evaluation. I would like to know which is the criteria to decide whether to use one or the other.
虽然 ASSERT_* 宏导致测试用例终止,但 EXPECT_* 宏继续其评估。我想知道决定使用一个还是另一个的标准是什么。
回答by GManNickG
Use ASSERT
when the condition musthold - if it doesn't the test stops right there. Use this when the remainder of the test doesn't have semantic meaning without this condition holding.
ASSERT
当条件必须成立时使用- 如果没有,测试就在那里停止。当测试的其余部分在没有此条件的情况下没有语义意义时使用此选项。
Use EXPECT
when the condition shouldhold, but in cases where it doesn't we can still get value out of continuing the test. (The test will still ultimately fail at the end, though.)
EXPECT
在条件应该成立时使用,但在条件不成立的情况下,我们仍然可以从继续测试中获得价值。(不过,测试最终仍会失败。)
The rule of thumb is: use EXPECT
by default, unless you requiresomething to hold for the remainder of the tests, in which case you should use ASSERT
for that particular condition.
经验法则是:EXPECT
默认使用,除非您需要为剩余的测试保留一些东西,在这种情况下,您应该ASSERT
在特定条件下使用。
This is echoed within the primer:
这在引文中得到了回应:
Usually
EXPECT_*
are preferred, as they allow more than one failures to be reported in a test. However, you should useASSERT_*
if it doesn't make sense to continue when the assertion in question fails.
通常
EXPECT_*
是首选,因为它们允许在测试中报告多个失败。但是,ASSERT_*
如果在相关断言失败时继续没有意义,您应该使用。
回答by nabulke
Use EXPECT_
when you
EXPECT_
当你使用
- want to report more than one failure in your test
- 想要在测试中报告不止一个失败
Use ASSERT_
when
使用ASSERT_
时
- it doesn't make sense to continue when the assertion fails
- 当断言失败时继续是没有意义的
Since ASSERT_
aborts your function immediately if it fails, possible cleanup code is skipped.
Prefer EXPECT_
as your default.
由于ASSERT_
如果函数失败会立即中止您的函数,因此可能会跳过可能的清理代码。首选EXPECT_
作为您的默认值。
回答by Martin G
In addition to previous answers...
除了之前的回答...
ASSERT_
does not terminate execution of the test case. It returns from whatever function is was used in. Besides failing the test case, it evaluates to return;
, and this means that it cannot be used in a function returning something other than void
. Unless you're fine with the compiler warning, that is.
ASSERT_
不会终止测试用例的执行。它从任何使用过的函数返回。除了测试用例失败外,它的计算结果为return;
,这意味着它不能用于返回除 之外的其他内容的函数中void
。除非您对编译器警告没有意见,否则。
EXPECT_
fails the test case but does not return;
, so it can be used inside functions of any return type.
EXPECT_
测试用例失败但没有失败return;
,因此它可以在任何返回类型的函数中使用。
回答by ratkok
Check the following link: Effective C++ Testing Using GoogleTest(slide 23). There is a good guideline/advice on the use of EXPECT vs ASSERT.
检查以下链接:使用 GoogleTest 进行有效的 C++ 测试(幻灯片 23)。关于使用 EXPECT 与 ASSERT 有一个很好的指南/建议。