2013-03-16 31 views
0

我一直在試圖在Google C++ Testing Framework/gtest中找到斷言,這相當於在Boost Test Library中找到的BOOST_CHECK_EQUAL_COLLECTIONS斷言。BOOST_CHECK_EQUAL_COLLECTIONS在Google測試中

但是;沒有成功。所以我的問題是雙重的:

  1. gtest是否有一個等效的斷言?
  2. 如果不是:如何在gtest中聲明容器內容?

EDIT(略作修改答案):

#include <iostream> 

template<typename LeftIter, typename RightIter> 
::testing::AssertionResult CheckEqualCollections(LeftIter left_begin, 
               LeftIter left_end, 
               RightIter right_begin) 
{ 
    std::stringstream message; 
    std::size_t index(0); 
    bool equal(true); 

    for(;left_begin != left_end; left_begin++, right_begin++) { 
     if (*left_begin != *right_begin) { 
      equal = false; 
      message << "\n Mismatch in position " << index << ": " << *left_begin << " != " << *right_begin; 
     } 
     ++index; 
    } 
    if (message.str().size()) { 
     message << "\n"; 
    } 
    return equal ? ::testing::AssertionSuccess() : 
        ::testing::AssertionFailure() << message.str(); 
} 
+0

我想你需要看看姊妹項目:Google Mock。 – 2013-03-16 11:22:04

回答

0

我不知道一個完全等同GTEST斷言。但是,下面的功能應該提供類似的功能:

template<typename LeftIter, typename RightIter> 
::testing::AssertionResult CheckEqualCollections(LeftIter left_begin, 
               LeftIter left_end, 
               RightIter right_begin) { 
    bool equal(true); 
    std::string message; 
    std::size_t index(0); 
    while (left_begin != left_end) { 
    if (*left_begin++ != *right_begin++) { 
     equal = false; 
     message += "\n\tMismatch at index " + std::to_string(index); 
    } 
    ++index; 
    } 
    if (message.size()) 
    message += "\n\t"; 
    return equal ? ::testing::AssertionSuccess() : 
       ::testing::AssertionFailure() << message; 
} 

using a function that returns an AssertionResult的章節介紹如何使用此全部細節,但它會是這樣的:

EXPECT_TRUE(CheckEqualCollections(collection1.begin(), 
            collection1.end(), 
            collection2.begin())); 
2

亞歷克斯指出,GTEST有一個名爲谷歌模擬一個姊妹項目,它具有優良的設施比較兩個容器:

EXPECT_THAT(actual, ContainerEq(expected)); 
// ElementsAre accepts up to ten parameters. 
EXPECT_THAT(actual, ElementsAre(a, b, c)); 
EXPECT_THAT(actual, ElementsAreArray(array)); 

您將在獲取更多210。