开发者

Using ASSERT and EXPECT in GoogleTest

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.


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 use ASSERT for that particular condition.


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 use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.


Use EXPECT_ when you

  • want to report more than one failure in your test

Use ASSERT_ when

  • 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.


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.

EXPECT_ fails the test case but does not return;, so it can be used inside functions of any return type.


Google C++ Testing Framework supports two families of assertions with the same interface:

  • ASSERT: Fails fast, aborting the current function.
  • EXPECT: Continues after the failure.

EXPECT is often more appropriate because it: reveals more failures in a single run, and allows more to be fixed in a single edit/compile/run-tests cycle.

Example:

TEST(WordStemmerTest, StemsPluralSuffixes) 
{  
  EXPECT_STREQ("jump", stemmer->Stem("jumps"));  
  EXPECT_STREQ("pixi", stemmer->Stem("pixies"));  
  EXPECT_STREQ("prioriti", stemmer->Stem("priorities"));  
  // etc ...
}

Use ASSERT when it doesn't make sense to continue.

Example:

TEST(FileGeneratorTest, CreatesFileContainingSequenceOfChars) 
{  
  ASSERT_TRUE(fp = fopen(path, "r"))        << "Failed to open " << path;  
  ASSERT_EQ(10, fread(buffer, 1, 10, fp))        << "File " << path << " is too small";  buffer[10] = '\0';  
  EXPECT_STREQ("123456789", buffer)        << "File " << path << " is corrupted";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜