Google 테스트의 배열 비교?
Google 테스트에서 두 배열을 비교하려고합니다. UnitTest ++에서는 CHECK_ARRAY_EQUAL을 통해 수행됩니다. Google 테스트에서 어떻게합니까?
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), _));
가능한 모든 상황에 대해 많은 매 처가 있으며 이들을 결합하여 거의 모든 것을 달성 할 수 있습니다.
수업에 ElementsAre
필요한 방법 iterators
과 size()
방법 만 말씀 드렸나요 ? 따라서 STL의 모든 컨테이너뿐만 아니라 사용자 지정 컨테이너에서도 작동합니다.
Google Mock은 Google Test만큼 이식성이 있다고 주장하며 솔직히 왜 그것을 사용하지 않는지 모르겠습니다. 순전히 굉장합니다.
배열이 동일한 지 확인해야하는 경우 무차별 대입도 작동합니다.
int arr1[10];
int arr2[10];
// initialize arr1 and arr2
EXPECT_TRUE( 0 == std::memcmp( arr1, arr2, sizeof( arr1 ) ) );
그러나 이것은 어떤 요소가 다른지 알려주지 않습니다.
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));
나는 이것을 합치려고 너무 오래 보냈다. std :: vector 반복기 초기화에 대한 알림에 대한 이 StackOverlow 게시물 에 감사드립니다 . 이 메서드는 비교 전에 버퍼 배열 요소를 std :: vector에 복사합니다.
나는 똑같은 질문을 했으므로 두 개의 일반 컨테이너를 비교하는 몇 가지 매크로를 작성했습니다. 그것은이 모든 컨테이너에 확장이다 const_iterator
, begin
하고 end
. 실패하면 배열이 어디에서 잘못되었는지에 대한 자세한 메시지를 표시하고 실패한 모든 요소에 대해 그렇게합니다. 길이가 같은지 확인합니다. 코드에서 실패한 것으로보고하는 위치는을 호출하는 동일한 줄 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 )
이것이 당신에게 효과가 있기를 바랍니다 (그리고 질문이 제출 된 지 두 달 후에 실제로이 답변을 확인하십시오).
Google 테스트 에서 배열을 비교하는 것과 비슷한 문제가 발생했습니다 .
Since I needed comparison with basic void*
and char*
(for low-level code testing), I don't thing either google mock (which I'm also using in the project) or Seth's great macro could help me in the particular situation. I wrote the following macro:
#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]);\
}\
}
The casts are there to make the macro usable when comparing void*
to other stuff:
void* retrieved = ptr->getData();
EXPECT_EQ(6, ptr->getSize());
EXPECT_ARRAY_EQ(char, "data53", retrieved, 6)
Tobias in the comments suggested casting void*
to char*
and using EXPECT_STREQ
, a macro I somehow missed before - which looks like a better alternative.
Below is an assertion I wrote to compare [fragments of] two floating point arrays:
/* 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();
}
Usage within the Google Testing Framework is this:
EXPECT_TRUE(AreFloatingPointArraysEqual(expectedArray, actualArray, lengthToCompare));
In case of an error, something like the following output is produced:
..\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
For thorough discussion on comparing floating point values in general, please see this.
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;
}
I used a classic loop through all elements. You can use SCOPED_TRACE to read out in which iteration the array elements differ. This provides you with additional information compared to some other approaches and is easy to read.
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]);
}
참고URL : https://stackoverflow.com/questions/1460703/comparison-of-arrays-in-google-test
'programing tip' 카테고리의 다른 글
moment.js에서 초를 HH : mm : ss로 변환하는 방법 (0) | 2020.11.04 |
---|---|
로컬 .json 파일을 읽는 Angular 5 서비스 (0) | 2020.11.04 |
느낌표를 어떻게 피할 수 있습니까! (0) | 2020.11.04 |
JSON 개체 이름 / 값에 액세스하는 방법은 무엇입니까? (0) | 2020.11.04 |
HTML SELECT-JavaScript를 사용하여 선택한 옵션을 VALUE로 변경 (0) | 2020.11.04 |