Search code examples
googletest

Googletest: messages are not printed on successful assertion


I'm trying to emit warnings in successful unit-tests, created with GTest.

I expect that code below prints "My warning message" somewhere:

#include <gtest/gtest.h>

GTEST_API_ int main(int argc, char** argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

TEST(suite, name)
{
    EXPECT_TRUE(true) << "My warning message";
}

However, I don't see expected string neither in console, nor in XML files.

I've tried stepping the code in the debugger and have seen that that string is stored in the object of class ::testing::AssertionResult created inside the macro EXPECT_TRUE.

However, it is unclear what to do to make it appear.

Updating Googletest to the head of master branch doesn't help.


Solution

  • All the assertions/expectations print the custom message only if the assertion fails. In the case of this expectation:

    EXPECT_TRUE(true) << "My warning message";
    

    it will never be triggered. You can confirm this by calling:

    EXPECT_TRUE(false) << "My warning message";
    

    using this will however make your test to fail. If you want to have messages printed when the tests is successful, you can use SUCCEED and a custom TestEventListener:

    class SuccessListener : public testing::EmptyTestEventListener {
      void OnTestPartResult(const testing::TestPartResult& result) override {
        if (result.type() == testing::TestPartResult::kSuccess) {
          printf("%s\n", result.message());
        }
      }
    };
    
    int main(int argc, char* argv[]) {
        ::testing::InitGoogleTest(&argc, argv);
        testing::UnitTest::GetInstance()->listeners().Append(new SuccessListener);
        return RUN_ALL_TESTS();
    }
    
    
    TEST(SuccessPrintTest, SuccessPrint) {
        SUCCEED() << "Custom message";
    }
    

    The output is:

    [ RUN      ] SuccessPrintTest.SuccessPrint
    Succeeded
    Custom message
    [       OK ] SuccessPrintTest.SuccessPrint (0 ms)
    

    This will be quite verbose though if printed to the console - you may want to redirect it to a file (which would be handled by SuccessListener).