views:

54

answers:

2

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?

+5  A: 

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.

mskfisher
@mskfisher - this is in the docs, it's just well-hidden
Steve Townsend
Yeah, I'm busy editing away my shame. :) Thanks for your examples in your answer.
mskfisher
+3  A: 

How about BOOST_CHECK_EQUAL_COLLECTIONS?

BOOST_AUTO_TEST_CASE( test )
{
    int col1 [] = { 1, 2, 3, 4, 5, 6, 7 };
    int col2 [] = { 1, 2, 4, 4, 5, 7, 7 };

    BOOST_CHECK_EQUAL_COLLECTIONS( col1, col1+7, col2, col2+7 );
}

example

Running 1 test case...

test.cpp(11): error in "test": check { col1, col1+7 } == { col2, col2+7 } failed.

Mismatch in a position 2: 3 != 4

Mismatch in a position 5: 6 != 7

* 1 failure detected in test suite "example"

Steve Townsend