2014-03-13 109 views
0
// Filter.h/cpp 
class Filter 
{ 
public: 
    int readInt(int* value) 
    { 
     if (value == NULL) 
      return 0; 

     *value = 15; // some logical; 
     return 1; 
    } 
}; 


// TestTee.h/.cpp 
class TestTee 
{ 
public: 
    Func1(Filter* f) 
    { 
     ... 
     int val; 
     f->readInt(&val); 
     ... 
    } 
} 

現在,我需要測試TestTee課,所以我嘲笑類Filter如何使用Google測試來測試將調用包含輸出參數的另一個函數的函數?

class MockFilter : public Filter 
{ 
public: 
    MOCK_METHOD1(readInt, int(int*)); 
}; 

如何編寫測試用例?

TEST_F(TestClass, Test1) 
{ 
    TestTee t; 
    MockFilter filter; 

    EXPECT_CALL(filter, readInt(_)).Times(1); // failed error:  The mock function has no default action set, and its return type has no default value set." thrown in the test body. 
    /* 
    int val; 
    EXPECT_CALL(filter, readInt(&val)).Times(1); 

    Failed with the following error: 
      Expected: to be called once 
      Actual: never called - unsatisfied and active 
    */ 
    t.Func1(&filter); 
} 

所以,我的問題是

我不知道如何控制,這將在我的測試對象的功能代碼調用函數的輸出參數。

有何評論?多謝。

回答

0

首先,不要忘記,一個功能需要被虛擬GoogleMock才能夠真正嘲笑它:

class Filter 
{ 
public: 
    virtual int readInt(int* value) 
    { 
     if (value == NULL) 
      return 0; 

     *value = 15; // some logical; 
     return 1; 
    } 
}; 

測試代碼取決於你真正想要測試的內容。如果你只想確保過濾::的readInt叫這應該是足夠了:

TEST_F(TestClass, Test1) 
{ 
    TestTee t; 
    MockFilter filter; 

    EXPECT_CALL(filter, readInt(_)); 

    t.Func1(&filter); 
} 

(因爲已的readInt內置的返回類型(INT)GoogleMock應該能夠找出默認的返回值不抱怨)。

如果你想確保的readInt被稱爲例如只有一次,使用次數子句:

EXPECT_CALL(filter, readInt(_)).Times(1); 

如果你想測試對象的繼的readInt通話測試過程中獲得足夠的回報值,也就是說,如果代碼你需要一個模擬模擬返回的值對於返回值使用Return子句,對於通過指針傳遞的輸出值的SetArgPointee子句,或者兩者都是這樣的:

EXPECT_CALL(filter, readInt(_)).WillOnce(DoAll(SetArgPointee<0>(15), Return(1))); 
相關問題