I am using Boost Test to unit test some C++ code.
I have a vector of values that I need to compare with expected results, but I don't want to manually check the values in a loop:
BOOST_REQUIRE_EQUAL(values.size(), expected.size()); for( int i = 0; i < size; ++i ) { BOOST_CHECK_EQUAL(values[i], expected[i]); }
The main problem is that the loop check doesn't print the index, so it requires some searching to find the mismatch.
I could use std::equal
or std::mismatch
on the two vectors, but that will require a lot of boilerplate as well.
Is there a cleaner way to do this?
Use BOOST_CHECK_EQUAL_COLLECTIONS
. It's a macro in test_tools.hpp
that takes two pairs of iterators:
BOOST_CHECK_EQUAL_COLLECTIONS(values.begin(), values.end(), expected.begin(), expected.end());
It will report the indexes and the values that mismatch. If the sizes don't match, it will report that as well (and won't just run off the end of the vector).
Note that if you want to use BOOST_CHECK_EQUAL
or BOOST_CHECK_EQUAL_COLLECTIONS
with non-POD types, you will need to implement
bool YourType::operator!=(const YourType &rhs) // or OtherType std::ostream &operator<<(std::ostream &os, const YourType &yt)
for the comparison and logging, respectively.
The order of the iterators passed to BOOST_CHECK_EQUAL_COLLECTIONS
determines which is the RHS and LHS of the !=
comparison - the first iterator range will be the LHS in the comparisons.
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