Oneliner for testing std::vector contents
-
25-07-2021 - |
Question
What is a more convenient way of doing this:
EXPECT_EQ(mock->params.size(), 2);
EXPECT_EQ(mock->params[0], "firstCall");
EXPECT_EQ(mock->params[1], "secondCall");
One problem with the above is that the test cases will crash when doing test driven development where the size of mock->params will first be zero before the actual code under test is written.
BTW, I am not allowed to use GoogleMock since it needs certain compiler flags which I can't use. I can use std and boost.
Solution
You may try to use Boost.Assign. For instance, list_of sequence can be compared with vector:
#include <iostream>
#include <ostream>
#include <vector>
#include <boost/assign/list_of.hpp>
using namespace std;
using namespace boost::assign;
int main()
{
vector<int> v;
v.push_back(0);
v.push_back(1);
cout << (v == list_of(0)(1) ) << endl;
cout << (v == list_of(1) ) << endl;
cout << (v == list_of(1)(2) ) << endl;
}
Output is:
1
0
0
OTHER TIPS
Not a one liner but should do what you want:
std::vector<std::string> expected;
expected.push_back("firstCall");
expected.push_back("secondCall");
EXPECT_EQ(mock->params,expected);
Otherwise I would recommend to use ASSERT_EQ()
for the first test to prevent your test case from crashing as @Rook states in his comment (that's what it's designed for).
UPDATE: Using Boost Assign as @Evgeny Panasyuk's answer suggests it should look like this:
EXPECT_EQ(mock->params,list_of("firstCall")("secondCall"));
If I understood this correctly (its not so clear from the answer, and I've personally never used this).
You can use Google Mock's (Google Mock is Google Test's companion mocking framework) rich library of matchers to write clear looking test assertions:
#include <gtest.h>
#include <gmock.h>
using testing::ElementsAre;
TEST(Foo, Bar) {
EXPECT_THAT(mock->params, ElementsAre("firstCall", "secondCall"));
}
That assertion also produces clear message when the tested condition is violated.