Pages

Binary comparisons

We could just use ASSERT_TRUE and EXPECT_TRUE, and their *_FALSE counterparts, to do all our testing job with Google Test.

But there is a bunch of other assertions and expectations that make our testing more readable. Binary comparisons support comparison between the expected and the actual result of a test using the comparison operators == (ASSERT_EQ, EXPECT_EQ), != (ASSERT_NE, EXPECT_NE), < (ASSERT_LT, EXPECT_LT), <= (ASSERT_LE, EXPECT_LE), > (ASSERT_GT, EXPECT_GT), >= (ASSERT_GE, EXPECT_GE).

Let's see them in action:

TEST(BinaryComparison, Equal) {
int expected = 40;

EXPECT_TRUE(expected == increase(41)); // 1.
EXPECT_EQ(expected, increase(41)); // 2.
EXPECT_EQ(40, increase(41));
EXPECT_NE(42, increase(41));
}

I've used only EXPECT tests, but the ASSERT ones work just the same.
1. We could use EXPECT_TRUE, but the generated message is a bit less readable.
2. We could put a variable or a literal as expected value. In case of a variable, the error message would report its name and value.

Here is the messages as showed by Guitar (the application runner for Google Test):

(..)\test.cpp(18): error: Value of: expected == increase(41)
Actual: false
Expected: true
(..)\test.cpp(19): error: Value of: increase(41)
Actual: 42
Expected: expected
Which is: 40
(..)\test.cpp(20): error: Value of: increase(41)
Actual: 42
Expected: 40
(..)\test.cpp(21): error: Expected: (42) != (increase(41)), actual: 42 vs 42

Let's check now the Less / LessEqual tests:

TEST(BinaryComparison, Less) {
int expected = 40;

EXPECT_LT(expected, increase(39));
EXPECT_LE(expected, increase(38));
}

Here is the feedback from Guitar:

(..)\test.cpp(27): error: Expected: (expected) < (increase(39)), actual: 40 vs 40
(..)\test.cpp(28): error: Expected: (expected) <= (increase(38)), actual: 40 vs 39

And, finally, Greater / GreaterEqual:

TEST(TestIncrease, Greater) {
int expected = 40;

EXPECT_GT(expected, increase(39));
EXPECT_GE(expected, increase(40));
}

with the relative output on Guitar:

(..)\test.cpp(34): error: Expected: (expected) > (increase(39)), actual: 40 vs 40
(..)\test.cpp(35): error: Expected: (expected) >= (increase(40)), actual: 40 vs 41

No comments:

Post a Comment