0

I'm trying to figure out how to compare strings in error messages using EXPECT_EXIT from GoogleTest. Everything works fine when I add common characters, but it doesn't work for characters like [](){}. When I run it the test it fails. See the following output:

[ RUN      ] MyDeathTest.ExitFailure
main.c:10: Failure
Death test: myFunction()
    Result: died but not with expected error.
  Expected: contains regular expression "Error: expected [10]"
Actual msg:
[  DEATH   ] Error: expected [10]
[  FAILED  ] MyDeathTest.ExitFailure (0 ms)
[----------] 1 test from MyDeathTest (0 ms total)

Here is my C program.

#include <gtest/gtest.h>    
#include <stdio.h>    
    
int myFunction(){    
  fprintf(stderr, "Error: expected [%d]", 10);   
  exit(EXIT_FAILURE);    
}    
                                                                                                                                              
TEST(MyDeathTest, ExitFailure) {                                                                                                              
  EXPECT_EXIT(myFunction(), testing::ExitedWithCode(1), "Error: expected [10]");                                                              
}                                                                                                                                             
                                                                                                                                              
// g++ main.c -lgtest -lgtest_main -pthread && ./a.out                                                                                        
int main(int argc, char *argv[]) {                                                                                                            
  testing::InitGoogleTest(&argc, argv);                                                                                                       
  return RUN_ALL_TESTS();                                                                                                                     
}                          

The error message is the same, but I think GoogleTest can't handle regular expressions. What is going on? How can I fix it?

  • 4
    `[10]` in regular expressions means "single character, either `1` or `0`". Not sure what is the proper fix, never worked with death tests, I guess you need `"Error: expected \\[10\\]"` or with C++11 raw string literal `R"(Error: expected \[10\])"` – Yksisarvinen May 28 '22 at 19:03
  • 1
    @Yksisarvinen No, [buffers are flushed automatically at exit](https://stackoverflow.com/questions/15911517/is-there-a-guarantee-of-stdout-auto-flush-before-exit-how-does-it-work). – Thomas May 28 '22 at 19:35
  • @Thomas Right, I got confused with the way GTest formats death test output. It indeed prints, but the line is prefixed with `[ DEATH ]` – Yksisarvinen May 28 '22 at 19:40

0 Answers0