TotT: EXPECT vs. ASSERT
July 10th, 2008 | Published in Google Testing
Because the Google C++ Testing Framework was opensourced last week, there will be episodes focusing on it published here in the future. Watch for them. I've reshuffled the schedule to get one out this week.
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.
As Moka the code monkey has shown Uni the testing robot, 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"))
ASSERT_EQ(10, fread(buffer, 1, 10, fp))
buffer[10] = '\0';
EXPECT_STREQ("123456789", buffer)
}
Remember to download this episode of Testing on the Toilet and post it in your office.