Google テストで 2 つの配列を比較しようとしています。UnitTest++ では、これは CHECK_ARRAY_EQUAL を通じて行われます。Googleテストでどのようにしますか?
10 に答える
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
だけが必要だと言いましたか? そのため、STL のコンテナーだけでなく、カスタム コンテナーでも機能します。iterators
size()
Google Mock は、Google Test とほぼ同じくらい移植可能であると主張していますが、率直に言って、あなたがそれを使用しない理由がわかりません。それは純粋に素晴らしいです。
配列が等しいかどうかを確認するだけの場合は、ブルート フォースも機能します。
int arr1[10];
int arr2[10];
// initialize arr1 and arr2
EXPECT_TRUE( 0 == std::memcmp( arr1, arr2, sizeof( arr1 ) ) );
ただし、これはどの要素が異なるかを示しているわけではありません。
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;
}
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 は、2 つの C スタイル配列ポインターの比較を可能にするポインターと長さも受け入れます。例えば:
ASSERT_THAT(std::vector<uint8_t>(buffer, buffer + buffer_size),
::testing::ElementsAreArray(buffer, buffer_size));
これをつなぎ合わせるのに非常に長い時間を費やしました。std::vector イテレータの初期化に関するリマインダーについては、この StackOverflow の投稿に感謝します。このメソッドは、比較の前にバッファー配列要素を std::vector にコピーすることに注意してください。
まったく同じ質問があったので、2 つの汎用コンテナーを比較するマクロをいくつか作成しました。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 )
これがうまくいくことを願っています (そして、質問が送信されてから 2 か月後にこの回答を実際に確認してください)。
すべての要素に古典的なループを使用しました。SCOPED_TRACE を使用して、配列要素が異なる反復を読み取ることができます。これにより、他のアプローチと比較して追加情報が得られ、読みやすくなります。
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]);
}
Google testで配列を比較すると、同様の問題が発生しました。
void*
基本的なand (低レベルのコード テスト用) との比較が必要だったので、特定の状況ではGoogle Mock (プロジェクトでも使用しています) や Seth の優れたマクロが役立つとchar*
は思いません。次のマクロを書きました。
#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]);\
}\
}
void*
キャストは、他のものと比較するときにマクロを使用できるようにするためにあります。
void* retrieved = ptr->getData();
EXPECT_EQ(6, ptr->getSize());
EXPECT_ARRAY_EQ(char, "data53", retrieved, 6)
コメントのTobiasは、私が以前に見逃していたマクロにキャストvoid*
しchar*
て使用することを提案しました-これはより良い代替手段のように見えます.EXPECT_STREQ
以下は、2 つの浮動小数点配列 [のフラグメント] を比較するために私が書いたアサーションです。
/* 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();
}
Google テスト フレームワーク内での使用法は次のとおりです。
EXPECT_TRUE(AreFloatingPointArraysEqual(expectedArray, actualArray, lengthToCompare));
エラーが発生した場合、次のような出力が生成されます。
..\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
一般的な浮動小数点値の比較に関する詳細な説明については、こちらを参照 してください。