2017-04-14 49 views
0

在googlemock和googletest的幫助下,我設置了一個測試,用於檢查被測試的方法是否正確處理了不同的模擬錯誤。基本上我的代碼如下所示:googlemock具有較小行爲變化的EXPECT_CALL

// setup mock object, and object under test 

    // setup initial EXPECT_CALL expectations 

    // this expected method call in the middle mocks a failure 
    EXPECT_CALL(*mock, method(arg_in)). 
    Times(1). 
    WillOnce(Throw(exception_of_type_A)); 

    // setup cleanup EXPECT_CALL expectations 

    // Now invoke method in object under test. 
    // Expect exception has been translated to different type. 
    EXPECT_THROW(x.method_under_test(), exception_type_B); 

    // destructor of mock object will check the mock method invocations 

既然無法在這裏不僅可以通過拋型A的異常失敗,但也通過投擲B型的異常我模擬的方法,或者通過返回一個意外的返回值。

我可以通過複製和粘貼完整的TEST()並且只是改變行爲不當的模擬方法將做的事情來輕鬆實現這一點。但這會使代碼變得混亂。即使我記載這3個測試除了在WillOnce()動作規範中的模擬方法1失敗之外完全相同,如果這仍然是真的,人類讀者仍然必須仔細比較。

什麼是正確的方式在googletest/googlemock共享三個測試之間的共同代碼,只是讓他們在WillOnce()行動有所不同?

我的腦海裏出現了:宏,用WillOnce()動作循環遍歷一個容器,googletest fixtures,用於設置和清理的靜態輔助方法。

我還是googletest的新手,不確定如何解決這個問題。

回答

0

現在,我實現一個接受動作爲參數的模板靜態函數測試邏輯:

template <typename A> 
static void paramererizeable_test(A failingAction) { 
    // set everything up 
    EXPECT_CALL(*mock, method(arg_in)). 
    Times(1). 
    WillOnce(failingAction); 
    // set up more expectations 
    // trigger the calls 
} 

TEST(Section, Method) { 
    paramererizeable_test(Throw(exception_of_type_A)); 
    paramererizeable_test(Throw(exception_of_type_B)); 
    paramererizeable_test(Return(unexpected_return_value)); 
} 

不知道這是怎麼了應該做的,或者是否有更好的辦法,但它的工作原理和可讀性。