Search code examples
c++unit-testinggoogletestgooglemock

EXPECT_DEATH with GMock - failed to die


  1. I have created a mock of an external socket api in my_inet.cpp file.
  2. GMock functions for that socket api is in mock.h file.
  3. I am using my created socket api of my_inet in server.cpp file.
  4. The test is written in gtest.cpp.

I want to execute a death case successfully through exit(1) but GMock says that "failed to die".

Why?

gtest.cpp

TEST(MyTest, SocketConnectionFail)
{
    MockMyTCPAPI obj_myTCP;

    Server obj_server( &obj_myTCP );

    EXPECT_DEATH( obj_server.InitializeSocket(), "No socket connection!");
}

server.cpp

int Server::InitializeSocket()
{
  if( ret_val_socket == -1 )
  {
        ret_val_socket = myTCPAPI->socket( PF_INET, SOCK_STREAM, 0 );

        if( ret_val_socket == -1 )
        {
            printf( "\nNo socket connection!" );
            exit(1);
        }
        return ret_val_socket;
  }
  else
  {
        printf( "Warning! Attempting to create socket again. %d" , ret_val_socket);
        return 2;
  }

  return 0;
}

my_inet.cpp

int MyTCPAPI::socket( int arg1, int arg2, int arg3 )
{
        return -1;
}

Output:

[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from MyTest
[ RUN      ] MyTest.SocketConnectionFail

[WARNING] /usr/src/gtest/src/gtest-death-test.cc:825:: Death tests use fork(), which is unsafe particularly in a threaded context. For this test, Google Test couldn't detect the number of threads.

GMOCK WARNING:
Uninteresting mock function call - returning default value.
    Function call: socket(1, 0, 0)
          Returns: 0
Stack trace:
/home/anisha/Documents/office/tdd/tcp/server/gtest.cpp:56: Failure
Death test: obj_server.InitializeSocket()
    Result: failed to die.
 Error msg:
[  DEATH   ] 
[  FAILED  ] MyTest.SocketConnectionFail (3 ms)
[----------] 1 test from MyTest (3 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (3 ms total)
[  PASSED  ] 0 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] MyTest.SocketConnectionFail

 1 FAILED TEST

Solution

  • The output explains the issue:

    GMOCK WARNING:
    Uninteresting mock function call - returning default value.
        Function call: socket(1, 0, 0)
              Returns: 0
    

    Which means myTCPAPI->socket(PF_INET, SOCK_STREAM, 0) returns 0, not -1.

    Since MockMyTCPAPI obj_myTCP is a mock object (not MyTCPAPI), it won't run MyTCPAPI::socket(). You need to specify its return value. Something like the following should help:

    EXPECT_CALL(obj_myTCP, socket(_, _, _))
      .WillRepeatedly(Return(-1));
    

    Or use MyTCPAPI instead of MockMyTCPAPI in your test.