12

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.

Akavall
  • 82,592
  • 51
  • 207
  • 251
  • 2
    You may still do `REQUIRE(vec_1 == vec_2);` – Jarod42 Aug 31 '14 at 16:26
  • @Jarod42 Yeah, thank you, this does work. The only thing is that if `vec_1` and `vec_2` are of different data types I get an error, instead of, say `false`. – Akavall Aug 31 '14 at 16:48
  • @Akavall It's won't compile if they are of different data types. That's how a strongly typed language is supposed to work. – Paul Manta Aug 31 '14 at 17:12

1 Answers1

14

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" }
Colin D Bennett
  • 11,294
  • 5
  • 49
  • 66
David G
  • 94,763
  • 41
  • 167
  • 253
  • Note: You can inline the vector also REQUIRE( split(input) == std::vector{"one", "two", "three"}); – lfmunoz Oct 29 '20 at 17:05