2012-11-03 25 views
5

我有一個單元測試,我需要運行200個可能的數據組合。 (生產實現具有要在配置文件中測試的數據,我知道如何模擬這些值)。我更喜歡nit爲每個組合單獨編寫測試用例,並使用某種方式循環訪問數據。有沒有使用谷歌測試C++的一些這樣的直接方式?如何使用谷歌測試C++運行數據組合

感謝, Karthick

+0

爲什麼不使用結構數組來保存測試數據,並通過每個條目循環?你可以只有一個測試用例來測試所有的組合。 –

+0

Hi Emile,感謝您的建議。當我嘗試時,如果一個組合失敗,它會停止測試用例繼續進行,並且不會正確報告成功率。在一天結束時,這些對我來說是不同的測試案例。 –

回答

11

你可以使用gtest的Value-parameterized tests這個。

將此與Combine(g1, g2, ..., gN)發生器結合使用聽起來像是您最好的選擇。

以下示例填充2 vector秒,int■一個和另一個的string s,則只需一個單一的測試夾具,創建測試在2點vector的可用值的每一種組合:

#include <iostream> 
#include <string> 
#include <tuple> 
#include <vector> 
#include "gtest/gtest.h" 

std::vector<int> ints; 
std::vector<std::string> strings; 

class CombinationsTest : 
    public ::testing::TestWithParam<std::tuple<int, std::string>> {}; 

TEST_P(CombinationsTest, Basic) { 
    std::cout << "int: "  << std::get<0>(GetParam()) 
      << " string: \"" << std::get<1>(GetParam()) 
      << "\"\n"; 
} 

INSTANTIATE_TEST_CASE_P(AllCombinations, 
         CombinationsTest, 
         ::testing::Combine(::testing::ValuesIn(ints), 
              ::testing::ValuesIn(strings))); 

int main(int argc, char **argv) { 
    for (int i = 0; i < 10; ++i) { 
    ints.push_back(i * 100); 
    strings.push_back(std::string("String ") + static_cast<char>(i + 65)); 
    } 
    testing::InitGoogleTest(&argc, argv); 
    return RUN_ALL_TESTS(); 
} 
+0

讓我試試這個,回到你身邊。 –

+0

完美地工作。非常感謝。 –

+0

真是可愛的小例子,謝謝。 – TimZaman

2

使用結構數組(叫,說,Combination)來保存您的測試數據和循環雖然在一次測試中的每個條目。使用EXPECT_EQ而不是ASSERT_EQ檢查每個組合,以便測試不會中止,並且您可以繼續檢查其他組合。

Combination,這樣你可以把它輸出到ostream超載operator<<

ostream& operator<<(ostream& os, const Combination& combo) 
{ 
    os << "(" << combo.field1 << ", " << combo.field2 << ")"; 
    return os; 
} 

超載operator==Combination,讓您可以輕鬆地比較平等兩個組合:

bool operator==(const Combination& c1, const Combination& c2) 
{ 
    return (c1.field1 == c2.field1) && (c1.field2 == c2.field2); 
} 

而且單元測試可能看起來像這樣:

TEST(myTestCase, myTestName) 
{ 
    int failureCount = 0; 
    for (each index i in expectedComboTable) 
    { 
     Combination expected = expectedComboTable[i]; 
     Combination actual = generateCombination(i); 
     EXPECT_EQ(expected, actual); 
     failureCount += (expected == actual) ? 0 : 1; 
    } 
    ASSERT_EQ(0, failureCount) << "some combinations failed"; 
} 
+0

讓我試試看,回到你身邊。 –

+0

Hi Emile,儘管這聽起來很簡單,但我仍然將預計測試用例的計數設置爲1,即使對於expectedComboTable中的100個組合也是如此。由於這個原因,我需要重做報告儀表板等,給出具有組合情況下失敗的組合的確切數量。太多的頭痛。所以,我將無法使用它。感謝這個想法。 –