我已阅读this official document,了解如何进行二元比较和字符串比较。
ASSERT_EQ和ASSERT_STREQ无法在数组比较情况下工作。
例如
li@li:~/poc$ g++ -I${GTEST_DIR}/include insertion_sort.cpp insertion_sort_unittest.cpp /home/li/libgtest.a -lpthread -o inser_unit
li@li:~/poc$ ./inser_unit
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from InsertionSortTest
[ RUN ] InsertionSortTest.Two
insertion_sort_unittest.cpp:18: Failure
Value of: two_sorted
Actual: { 2, 5 }
Expected: two
Which is: { 2, 5 }
[ FAILED ] InsertionSortTest.Two (1 ms)
[----------] 1 test from InsertionSortTest (1 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] InsertionSortTest.Two
1 FAILED TEST
insertion_sort_unittest.cpp
#include <limits.h>
#include "insertionsort.h"
#include "gtest/gtest.h"
namespace{
class InsertionSortTest : public ::testing::Test{
protected:
InsertionSortTest() {}
virtual ~InsertionSortTest() {}
virtual void SetUp() {}
virtual void TearDown() {}
};
TEST(InsertionSortTest, Two){
int two[] = {5, 2};
int two_sorted[] = {2, 5};
insertionSort(two, 2);
EXPECT_EQ(two, two_sorted);
}
}
int main(int argc, char **argv){
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
insertion_sort.cpp
#include "insertionsort.h"
void insertionSort(int *data, int size){
for (int i=1,j; i<size; i++){
int key = data[i];
for (j=i-1; j>=0; j--){
if (data[j] > key){
data[j+1]=data[j];
data[j]=key;
}
}
}
}
insertionsort.h
#ifndef INSERTIONSORT_H_
#define INSERTIONSORT_H_
void insertionSort(int *data, int size);
#endif
答案 0 :(得分:15)
如果您不想要,您不需要在googlemock上添加依赖项,您可以编写自己的简单函数返回testing::AssertionResult
,例如
template<typename T, size_t size>
::testing::AssertionResult ArraysMatch(const T (&expected)[size],
const T (&actual)[size]){
for (size_t i(0); i < size; ++i){
if (expected[i] != actual[i]){
return ::testing::AssertionFailure() << "array[" << i
<< "] (" << actual[i] << ") != expected[" << i
<< "] (" << expected[i] << ")";
}
}
return ::testing::AssertionSuccess();
}
然后在测试中,请致电:
EXPECT_TRUE(ArraysMatch(two_sorted, two));
答案 1 :(得分:6)
ASSERT_EQ
使用operator==
比较其参数。与operator==
相比较适用于std::vector
,但不适用于C ++中的C数组。原因是,当您尝试在表达式中使用C数组的值时,在大多数情况下,该值会衰减为指向存储数组的内存开头的指针。你最终比较了两个指针。在两个不同的C阵列的情况下,这些指针永远不会具有相同的值。
最简单的方法是使用Google Mock的ASSERT_THAT
宏和ContainerEq匹配器。而不是ASSERT_EQ
,写
ASSERT_THAT(two, ContainerEq(two_sorted));
答案 2 :(得分:1)
我认为写这样就足够了。
EXPECT_EQ(memcmp(two, two_sorted, 2 * sizeof(int)), 0);