在 GoogleTest 中使用 ASSERT 和 EXPECT
当 ASSERT_* 宏导致测试用例终止时,EXPECT_* 宏继续其评估。 我想知道决定是否使用其中之一的标准是什么。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当条件必须成立时使用
ASSERT
- 如果不成立,测试将立即停止。当测试的其余部分在不满足此条件的情况下不具有语义意义时,请使用此选项。当条件应该成立时使用
EXPECT
,但在不成立的情况下,我们仍然可以通过继续测试获得价值。 (不过,测试最终还是会失败。)经验法则是:默认使用
EXPECT
,除非您需要在剩下的时间里保存一些东西。测试,在这种情况下,您应该针对该特定条件使用 ASSERT。入门中也体现了这一点:
Use
ASSERT
when the condition must hold - 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.Use
EXPECT
when the condition should hold, 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.)The rule of thumb is: use
EXPECT
by default, unless you require something to hold for the remainder of the tests, in which case you should useASSERT
for that particular condition.This is echoed within the primer:
当您
请使用
EXPECT_
当请使用
ASSERT_
自ASSERT_
code> 如果函数失败,则立即中止函数,并跳过可能的清理代码。首选
EXPECT_
作为默认值。Use
EXPECT_
when youUse
ASSERT_
whenSince
ASSERT_
aborts your function immediately if it fails, possible cleanup code is skipped.Prefer
EXPECT_
as your default.除了之前的答案之外...
ASSERT_
不会终止测试用例的执行。它从使用的任何函数中返回。除了测试用例失败之外,它的计算结果为return;
,这意味着它不能在返回void
以外的函数中使用代码>.除非您对编译器警告感到满意,否则就是这样。EXPECT_
测试用例失败,但不return;
,因此它可以在任何返回类型的函数内部使用。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 toreturn;
, and this means that it cannot be used in a function returning something other thanvoid
. Unless you're fine with the compiler warning, that is.EXPECT_
fails the test case but does notreturn;
, so it can be used inside functions of any return type.ASSERT_*:
EXPECT_*:
ASSERT_*:
EXPECT_*: