Creating an 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 a temporary vector to store the expected values.

std::vector<int> expected({5,2,3, 15}); EXPECT_TRUE(Util::sameTwoVectors(result, expected)); 

Is it possible to make one line? In python, I can generate a list using "[...]".

 sameTwoVectors(members, [5,2,3,15]) 
+6
source share
2 answers

Since std::vector contains a constructor constructor that accepts std::initializer_list , you can use uniform initialization syntax if the sameTwoVectors function accepts a vector by value, rvalue reference, or const .

 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 performs only a simple comparison, you can eliminate it. Just use the comparison expression in its place when you call EXPECT_TRUE . The trade-off is that you must explicitly specify std::vector<int> rather than relying on the implicit conversion constructor. These are a few characters smaller and a little clearer what the expected result is.

 EXPECT_TRUE(result == std::vector<int>({5,2,3,15})); 
+3
source

If Util::sameTwoVectors expects a reference to const or just a value that you can (assuming C ++ 11 support ) write like this:

 EXPECT_TRUE(Util::sameTwoVectors(result, std::vector<int>{5, 2, 3, 15})); 
+1
source

Source: https://habr.com/ru/post/947384/


All Articles