Reputation: 190839
In unit test code in C++, when I need to compare two vectors, I create temporary vector to store expected values.
std::vector<int> expected({5,2,3, 15});
EXPECT_TRUE(Util::sameTwoVectors(result, expected));
Can I make it one line? In python, I can generate a list with "[...]".
sameTwoVectors(members, [5,2,3,15])
Upvotes: 6
Views: 151
Reputation: 20063
Since std::vector
includes an initializer-list constructor that takes a std::initializer_list
you can use the uniform initialization syntax as long as the sameTwoVectors
function accepts a vector by value, rvalue reference or const
reference.
namespace Util
{
bool sameTwoVectors(
const std::vector<int>& result,
const std::vector<int>& expected)
{
return result == expected;
}
}
int main()
{
std::vector<int> result;
EXPECT_TRUE(Util::sameTwoVectors(result, {5,2,3,15}));
}
Optionally, if sameTwoVectors
only does a simple comparison you can eliminate it. Just use a comparison expression in its place when you call EXPECT_TRUE
. The trade-off is that you have to specify std::vector<int>
explicitly instead of relying on the implicit conversion constructor. It's a couple of characters less and a bit clearer what the expected result is.
EXPECT_TRUE(result == std::vector<int>({5,2,3,15}));
Upvotes: 3