谷歌测试中阵列的比较?

时间:2009-09-22 15:12:29

标签: c++ unit-testing googletest

我希望在谷歌测试中比较两个数组。在UnitTest ++中,这是通过CHECK_ARRAY_EQUAL完成的。你是如何在谷歌测试中做到的?

8 个答案:

答案 0 :(得分:91)

我真的建议看Google C++ Mocking Framework。即使你不想模仿任何东西,它也允许你轻松地编写相当复杂的断言。

例如

//checks that vector v is {5, 10, 15}
ASSERT_THAT(v, ElementsAre(5, 10, 15));

//checks that map m only have elements 1 => 10, 2 => 20
ASSERT_THAT(m, ElementsAre(Pair(1, 10), Pair(2, 20)));

//checks that in vector v all the elements are greater than 10 and less than 20
ASSERT_THAT(v, Each(AllOf(Gt(10), Lt(20))));

//checks that vector v consist of 
//   5, number greater than 10, anything.
ASSERT_THAT(v, ElementsAre(5, Gt(10), _));

对于每种可能的情况都有很多matchers,您可以将它们组合起来以实现几乎任何目标。

我是否告诉过你,ElementsAre只需要iteratorssize()方法来上课?所以它不仅适用于STL的任何容器,也适用于自定义容器。

Google Mock声称几乎和Google Test一样便携,坦率地说,我不明白为什么你不会使用它。这真是太棒了。

答案 1 :(得分:14)

如果你只需要检查数组是否相等,那么强力也可以起作用:

int arr1[10];
int arr2[10];

// initialize arr1 and arr2

EXPECT_TRUE( 0 == std::memcmp( arr1, arr2, sizeof( arr1 ) ) );

但是,这并不能告诉您哪个元素有所不同。

答案 2 :(得分:12)

如果你想使用Google Mock将c风格的数组指针与数组进行比较,你可以浏览std :: vector。例如:

uint8_t expect[] = {1, 2, 3, 42};
uint8_t * buffer = expect;
uint32_t buffer_size = sizeof(expect) / sizeof(expect[0]);
ASSERT_THAT(std::vector<uint8_t>(buffer, buffer + buffer_size), 
            ::testing::ElementsAreArray(expect));

Google Mock的ElementsAreArray也接受指针和长度,可以比较两个c风格的数组指针。例如:

ASSERT_THAT(std::vector<uint8_t>(buffer, buffer + buffer_size), 
            ::testing::ElementsAreArray(buffer, buffer_size));

我花了很长时间试图把它拼凑起来。感谢this StackOverlow post关于std :: vector迭代器初始化的提醒。请注意,此方法将在比较之前将缓冲区数组元素复制到std :: vector中。

答案 3 :(得分:9)

我有完全相同的问题,所以我编写了几个宏来对两个通用容器进行比较。它可以扩展到具有const_iteratorbeginend的任何容器。如果失败,它将显示一个详细的消息,指出阵列出错的地方,并对每个失败的元素都这样做;它会确保它们的长度相同;并且代码中报告为失败的位置与您调用EXPECT_ITERABLE_EQ( std::vector< double >, a, b)的行相同。

//! Using the google test framework, check all elements of two containers
#define EXPECT_ITERABLE_BASE( PREDICATE, REFTYPE, TARTYPE, ref, target) \
    { \
    const REFTYPE& ref_(ref); \
    const TARTYPE& target_(target); \
    REFTYPE::const_iterator refIter = ref_.begin(); \
    TARTYPE::const_iterator tarIter = target_.begin(); \
    unsigned int i = 0; \
    while(refIter != ref_.end()) { \
        if ( tarIter == target_.end() ) { \
            ADD_FAILURE() << #target " has a smaller length than " #ref ; \
            break; \
        } \
        PREDICATE(* refIter, * tarIter) \
            << "Containers " #ref  " (refIter) and " #target " (tarIter)" \
               " differ at index " << i; \
        ++refIter; ++tarIter; ++i; \
    } \
    EXPECT_TRUE( tarIter == target_.end() ) \
        << #ref " has a smaller length than " #target ; \
    }

//! Check that all elements of two same-type containers are equal
#define EXPECT_ITERABLE_EQ( TYPE, ref, target) \
    EXPECT_ITERABLE_BASE( EXPECT_EQ, TYPE, TYPE, ref, target )

//! Check that all elements of two different-type containers are equal
#define EXPECT_ITERABLE_EQ2( REFTYPE, TARTYPE, ref, target) \
    EXPECT_ITERABLE_BASE( EXPECT_EQ, REFTYPE, TARTYPE, ref, target )

//! Check that all elements of two same-type containers of doubles are equal
#define EXPECT_ITERABLE_DOUBLE_EQ( TYPE, ref, target) \
    EXPECT_ITERABLE_BASE( EXPECT_DOUBLE_EQ, TYPE, TYPE, ref, target )

希望这对您有用(并且您在提交问题两个月后确实会检查此答案)。

答案 4 :(得分:4)

我在 google test 中比较数组时遇到了类似的问题。

由于我需要与基本void*char*进行比较(对于低级代码测试),我不是 google mock (我和# 39; m也在项目中使用)或Seth的宏观宏可以帮助我在特定情况下。我写了以下宏:

#define EXPECT_ARRAY_EQ(TARTYPE, reference, actual, element_count) \
    {\
    TARTYPE* reference_ = static_cast<TARTYPE *> (reference); \
    TARTYPE* actual_ = static_cast<TARTYPE *> (actual); \
    for(int cmp_i = 0; cmp_i < element_count; cmp_i++ ){\
      EXPECT_EQ(reference_[cmp_i], actual_[cmp_i]);\
    }\
    }

在将void*与其他内容进行比较时,使用强制转换来使宏可用:

  void* retrieved = ptr->getData();
  EXPECT_EQ(6, ptr->getSize());
  EXPECT_ARRAY_EQ(char, "data53", retrieved, 6)

Tobias在评论中建议将void*投射到char*并使用EXPECT_STREQ,这是我以前在某种程度上错过的宏 - 这看起来是更好的选择。

答案 5 :(得分:4)

下面是我写的一个断言,用于比较两个浮点数组的[片段]:

/* See
http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
for thorough information about comparing floating point values.
For this particular application we know that the value range is -1 to 1 (audio signal),
so we can compare to absolute delta of 1/2^22 which is the smallest representable value in
a 22-bit recording.
*/
const float FLOAT_INEQUALITY_TOLERANCE = float(1.0 / (1 << 22));


template <class T>
::testing::AssertionResult AreFloatingPointArraysEqual(
                                const T* const expected,
                                const T* const actual,
                                unsigned long length)
{
    ::testing::AssertionResult result = ::testing::AssertionFailure();
    int errorsFound = 0;
    const char* separator = " ";
    for (unsigned long index = 0; index < length; index++)
    {
        if (fabs(expected[index] - actual[index]) > FLOAT_INEQUALITY_TOLERANCE)
        {
            if (errorsFound == 0)
            {
                result << "Differences found:";
            }
            if (errorsFound < 3)
            {
                result << separator
                        << expected[index] << " != " << actual[index]
                        << " @ " << index;
                separator = ", ";
            }
            errorsFound++;
        }
    }
    if (errorsFound > 0)
    {
        result << separator << errorsFound << " differences in total";
        return result;
    }
    return ::testing::AssertionSuccess();
}

Google测试框架中的用法是:

EXPECT_TRUE(AreFloatingPointArraysEqual(expectedArray, actualArray, lengthToCompare));

如果出现错误,会产生以下输出:

..\MyLibraryTestMain.cpp:145: Failure
Value of: AreFloatingPointArraysEqual(expectedArray, actualArray, lengthToCompare)
  Actual: false (Differences found: 0.86119759082794189 != 0.86119747161865234 @ 14, -0.5552707314491272 != -0.55527061223983765 @ 24, 0.047732405364513397 != 0.04773232713341713 @ 36, 339 differences in total)
Expected: true

有关比较浮点值的详细讨论,请参阅 this

答案 6 :(得分:4)

ASSERT_EQ(x.size(), y.size()) << "Vectors x and y are of unequal length";

for (int i = 0; i < x.size(); ++i) {
  EXPECT_EQ(x[i], y[i]) << "Vectors x and y differ at index " << i;
}

Source

答案 7 :(得分:2)

我在所有元素中使用了经典循环。您可以使用SCOPED_TRACE读出数组元素在哪个迭代中的不同。与其他一些方法相比,这为您提供了额外的信息,并且易于阅读。

for (int idx=0; idx<ui16DataSize; idx++)
{
    SCOPED_TRACE(idx); //write to the console in which iteration the error occurred
    ASSERT_EQ(array1[idx],array2[idx]);
}