2017-07-14 171 views
2

定義的功能指針我正在使用一個框架,傳遞函數指針爲void*。我想要一個模擬函數返回一個函數指針,並且我想定義函數就地(就像lambda;它不起作用,如下所示)。GMock:如何返回由EXPECT_CALL()

一個最小的工作示例如下所示。

#include <gtest/gtest.h> 
#include <gmock/gmock.h> 

using namespace std; 
using namespace testing; 

class Original 
{ 
public: 
    typedef int(*fptr)(); 

    void Func() 
    { 
     void* f = Func2(); 
     fptr func = reinterpret_cast<fptr>(f); 
     if (func) { 
      int i = func(); 
      if (i == 1) { 
       //do something 
      } else if (i == 3) { 
       //NOTE my unit test should test this decision branch 
      } 
     } 
    } 

    static int Func3() {return 1;} 

    virtual void* Func2() {return (void*)&Func3;} 
}; 

class MyMock : public Original 
{ 
public: 
    MOCK_METHOD0(Func2, void*()); 
}; 

我的主要目標:我想擺脫這個功能,並且在EXPECT_CALL()內嵌定義它。見下文。

int MockFunc() {cout << "mock func" << endl; return 3;} 

測試用例:

TEST(MYTEST, Test) 
{ 
    MyMock m; 

    //WORKS: compiles and works as expected, 
    //but I do not want to use **MockFunc** 
    EXPECT_CALL(m, Func2()).Times(AtLeast(1)) 
     .WillRepeatedly(Return(&MockFunc)); 

    //DOES NOT WORK: Does not compile, of course 
    //(compiler message below this code block) 
    EXPECT_CALL(m, Func2()).Times(AtLeast(1)) 
     .WillRepeatedly(Return((void*)&([](){return 3;}))); 
    m.Func(); 
} 

main.cpp中:117:90:錯誤:服用的臨時[-fpermissive]

爲了完整起見,main()地址:

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

所以q再次問:我怎樣才能擺脫MockFunc()函數,並在Return()內就地定義它的內容?

回答

3

下面的語句應該工作:

EXPECT_CALL(m, Func2()).Times(AtLeast(1)).WillRepeatedly(Return((void*)(+([](){return 3;})))); 

它利用一個事實,即非捕獲lambda表達式衰變函數指針。
換句話說,表達式(+([](){return 3;})的結果類型是int(*)()。然後,您可以像以前一樣將它投射到void*。錯誤也應該消失,因爲你不再獲得臨時地址。

相關問題