I wrote a class to help me compare two std::vectors
that won't necessarily have the same length. The class itself is working fine, but GoogleTest isn't using the ==
operator, so using EXPECT_EQ(foo, bar)
fails while EXPECT_TRUE(foo == bar)
works:
#include <vector>
#include <gtest/gtest.h>
template<class T>
class MyVector: public std::vector<T> {
public:
MyVector(std::initializer_list<T> il)
: std::vector<T>(il){}
bool operator== (const std::vector<T>& other)
{
// Need to static_cast so we don't call this function recursively
if( this->size() < other.size() ) {
return (
static_cast<std::vector<T>&>(*this) == std::vector<T>(other.begin(), other.begin()+this->size())
);
} else if( this->size() > other.size() ) {
return (
std::vector<T>(this->begin(), this->begin()+other.size()) == other
);
}
return (static_cast<std::vector<T>&>(*this) == other);
}
};
TEST(SOME_TEST, TestMyVector) {
MyVector<int> foo {1, 2, 3, 4};
std::vector<int> bar {1, 2, 3, 4, 5};
EXPECT_TRUE(foo == bar);
EXPECT_TRUE(foo == (std::vector<int>{1, 2, 3, 4}));
EXPECT_TRUE(foo == (std::vector<int>{1, 2, 3}));
EXPECT_TRUE(foo == (std::vector<int>{1, 2, 3, 4, 5}));
EXPECT_EQ(foo, bar);
}
When I run the above test, I get:
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from SOME_TEST
[ RUN ] SOME_TEST.TestMyVector
./my_test.cpp:38: Failure
Expected equality of these values:
foo
Which is: { 1, 2, 3, 4 }
bar
Which is: { 1, 2, 3, 4, 5 }
[ FAILED ] SOME_TEST.TestMyVector (0 ms)
[----------] 1 test from SOME_TEST (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] SOME_TEST.TestMyVector
1 FAILED TEST
How can I tell GTest to use my class, or what function do I need to write so that EXPECT_EQ
works?
Thanks!