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])
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}));
If Util::sameTwoVectors
expects const reference or just a value you can (assuming C++11 support) write it like that
EXPECT_TRUE(Util::sameTwoVectors(result, std::vector<int>{5, 2, 3, 15}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With