4

Google Test assertions ASSERT_* are supposed to be used in the form of ASSERT_EQ(expected, actual) where the 1st parameter is expected value and the 2nd is actual value. But very often I see in existing codebase that these parameters are reversed like in this code:

TEST(test, test)
{
    ASSERT_EQ(foo(), 1);    
}

This is almost ok, but it produces a bit weird error message in case of test failure like: "the result of foo() was expected but actually it was 1". This seems to be a minor issue but is there any way to force correct order of expected and actual at compile time?

ks1322
  • 33,961
  • 14
  • 109
  • 164
  • 1
    AFAIK - it is not a case for newer version of google-test. I mean - in newer versions - none of these sides are treated as only expected nor only actual. Just update your google test version. – PiotrNycz Oct 23 '17 at 16:00

2 Answers2

2

You can use Hamcrest matchers from google mock:

ASSERT_THAT(foo(), Eq(1) );

This improve readability and force order of parameters.

Joan Esteban
  • 1,006
  • 12
  • 23
1

For me the best way avoiding wired messages is, doing it correctly, from the beginning!

Okay, that doesn't help for existing test wrongly written, but in all unit-testing Frameworks I know (C#, Java, C++) it is always the same:

ASSERT(EXPECTED, ACTUAL)

And if another developer is reading your tests he should rely on you that you've done it correctly in the past.

hfrmobile
  • 1,213
  • 16
  • 16
  • 1
    That's the problem, you can't rely on other people that they will do it correctly. – ks1322 Sep 11 '20 at 10:28
  • 1
    Depends .... when working in a team and the team agrees ;-) If it is not possible to rely on others, then also the "Hamcrest version" won't work when the other people just don't do it ;-) Indeed the messages have been improved in latest Google Test Framework that they are "not too wrong" when used wrong order of parameters. – hfrmobile Sep 12 '20 at 19:09