我已经阅读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
insert_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();
}
insert_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;
}
}
}
}
insertsort.h
#ifndef INSERTIONSORT_H_
#define INSERTIONSORT_H_
void insertionSort(int *data, int size);
#endif
最佳答案
如果您不想的话,不需要添加对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));