Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making unnamed container in c++ for temporary comparison in unit test

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])
like image 222
prosseek Avatar asked Jun 16 '13 01:06

prosseek


2 Answers

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}));
like image 115
Captain Obvlious Avatar answered Oct 23 '22 10:10

Captain Obvlious


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}));
like image 30
JJJ Avatar answered Oct 23 '22 10:10

JJJ