Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test that two std::vectors are equal using CATCH C++ unit test framework

I an new to using CATCH, and I wondering how one would go about testing whether two std::vectors are equal.

My very naive attempt is this:

#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <vector>

TEST_CASE( "are vectors equal", "vectors")
{
  std::vector<int> vec_1 = {1,2,3};
  std::vector<int> vec_2 = {1,2,3};

  REQUIRE (vec_1.size() == vec_2.size());

  for (int i = 0; i < vec_1.size(); ++i)
    REQUIRE (vec_1[i] == vec_2[i]);
}

Is there a better way to do this? Some thing like magic REQUIRE_VECTOR_EQUAL?

Also, my above solution, is passing if one array contained doubles {1.0, 2.0, 3.0}; It's fine if two vectors are not considered equal because of this.

like image 339
Akavall Avatar asked Aug 31 '14 16:08

Akavall


1 Answers

You can use operator==:

REQUIRE(vec_1 == vec_2)

The cool thing is that Catch produces fantastic output when the assertion fails, and not just a simple pass/fail:

../test/Array_Vector_Test.cpp:90: FAILED:
  CHECK( x == y )
with expansion:
  { "foo", "bar" }
  ==
  { "foo", "quux", "baz" }
like image 130
David G Avatar answered Oct 24 '22 12:10

David G