• 我已经在my_inet.cpp文件中创建了一个外部套接字api的模拟。
  • 该套接字API的
  • GMock函数位于mock.h文件中。
  • 我正在使用my_inet文件中创建的server.cpp套接字API。
  • 测试以gtest.cpp编写。

  • 我想通过exit(1)成功执行死亡案件,但GMock说“失败了”。

    为什么?

    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;
    }
    

    输出:
    [==========] 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
    

    最佳答案

    输出说明了该问题:

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

    这意味着myTCPAPI->socket(PF_INET, SOCK_STREAM, 0)返回0,而不是-1。

    由于MockMyTCPAPI obj_myTCP是模拟对象(不是MyTCPAPI),因此它将不会运行MyTCPAPI::socket()。您需要指定其返回值。类似以下内容应有所帮助:
    EXPECT_CALL(obj_myTCP, socket(_, _, _))
      .WillRepeatedly(Return(-1));
    

    或在测试中使用MyTCPAPI而不是MockMyTCPAPI

    关于c++ - 与GMock的EXPECT_DEATH-未能死亡,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55375912/

    10-09 14:55