您尝试使用的 gtest 匹配器,testing::UnorderedElementsAreArray
和 testing::ContainerEq 仅适用于 STL 样式容器的对象。
见the documentation。
您的 foo 是 C-style array 的 int。您的
expected_result 和 result 是指向 int 的指针。这些都不是 STL 风格的容器,
并且指针在任何意义上都不是容器。
您要测试的问题是N 是否以expected_result 开头的整数
是从result 开始的N 整数的任何排列,其中N 是数字
数组中的元素数量foo。
通过单个EXPECT... 调用测试该问题的唯一方法
是当您调用某个确切确定的函数时期望得到一个真实的结果
带有参数result 和expected_result 的问题并返回一个布尔判断(或可转换为布尔判断的东西)。
C++ 标准库(C++11 或更高版本)为此目的提供了一个通用函数:std::is_permutation,
您将按照图示应用:
#include <gtest/gtest.h>
#include <algorithm>
int * reverse(int in[], std::size_t len)
{
int * permute = new int[len];
std::reverse_copy(in,in + len,permute);
return permute;
}
TEST(reverse,is_correct)
{
int foo[] {1,2,3};
int* expected_result = foo;
std::size_t len = sizeof(foo)/sizeof(foo[0]);
int* result = reverse(foo,len);
EXPECT_TRUE(std::is_permutation(result,result + len,expected_result));
delete [] result;
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
输出:
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from reverse
[ RUN ] reverse.is_correct
[ OK ] reverse.is_correct (0 sec)
[----------] 1 test from reverse (0 sec total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[ PASSED ] 1 test.
请注意,使用 C 风格的数组要求您通过以下方式管理堆内存
手:
int * permute = new int[len];
...
...
delete [] result
这在 C++ 中是对堆泄漏或堆损坏的无故邀请
错误。对于固定大小的数组,请使用std::array。
对于动态大小的数组,请使用std::vector。
这样更好:
#include <gtest/gtest.h>
#include <algorithm>
#include <array>
template<std::size_t N>
std::array<int,N> reverse(std::array<int,N> const & in)
{
std::array<int,N> permute;
std::reverse_copy(in.begin(),in.end(),permute.begin());
return permute;
}
TEST(reverse,is_correct)
{
std::array<int,3> foo {1,2,3};
auto result = reverse(foo);
EXPECT_TRUE(std::is_permutation(result.begin(),result.end(),foo.begin()));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
而且,由于 std::array 和 std::vector 是 STL 风格的容器,你的
如果您使用其中任何一种,最初的尝试都会奏效:
#include <gmock/gmock.h>
#include <algorithm>
#include <array>
template<std::size_t N>
std::array<int,N> reverse(std::array<int,N> const & in)
{
std::array<int,N> permute;
std::reverse_copy(in.begin(),in.end(),permute.begin());
return permute;
}
TEST(reverse,is_correct)
{
std::array<int,3> foo {1,2,3};
auto result = reverse(foo);
EXPECT_THAT(foo,testing::UnorderedElementsAreArray(result));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}