gpt4 book ai didi

c++ - gtest 如何比较两个数组中的值?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:04 25 4
gpt4 key购买 nike

我已阅读 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();
}

插入排序.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;
}
}
}
}

插入排序.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));

关于c++ - gtest 如何比较两个数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10060110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com