断言迭代器在 CppUnit 中相等

Asserting iterators equality in CppUnit

本文关键字:CppUnit 迭代器 断言      更新时间:2023-10-16

我已经开始使用 CppUnit 库了。一切正常,但现在,我陷入了使用 CPPUNIT_ASSERT_EQUAL 断言迭代器的困境。所以有我的代码:

void TestingClass::test_adjacent_find()
{
    // Set up
    int a [5] = {1,2,3,3,5};
    int b [5] = {1,2,3,4,5};
    int c [1] = {1};
    std::list<int> lst;
    lst.push_back(1);
    lst.push_back(1);
    lst.push_back(5);
    // Check
    CPPUNIT_ASSERT_EQUAL(a+2, my_adjacent_find(a , a+5, pred_eq<int>));
    CPPUNIT_ASSERT_EQUAL(b+5, my_adjacent_find(b, b+5, pred_eq<int>));
    CPPUNIT_ASSERT_EQUAL(c+1, my_adjacent_find(c, c+1, pred_eq<int>));
    CPPUNIT_ASSERT_EQUAL(lst.begin(), lst.end()); // problem is here
}

当我运行此测试时,我收到以下错误。

/opt/local/include/cppunit/TestAssert.h:49:13: 
Invalid operands to binary expression 
('OStringStream' (aka 'basic_ostringstream<char>') 
and 'const std::_List_iterator<int>')

如果我用迭代器注释该行,那么它可以毫无问题地编译。那我做错了什么呢?我应该如何断言两个迭代器的相等性?顺便说一下,我使用 xcode 4.4。

请参阅TestAssert.h中的CPPUNIT_ASSERT_EQUAL宏文档:

#define CPPUNIT_ASSERT_EQUAL(expected,actual)

expectedactual参数的要求:

  • 它们完全属于同一类型
  • 它们可以使用运算符序列化为 std::strstream <<
  • 可以使用运算符 == 来比较它们。

最后两个要求(序列化和比较)可以通过专门CppUnit::assertion_traits来删除。

因此,问题的根本原因是std::list::iterator无法序列化为std::strstream。您需要按照文档描述为其编写自己的CppUnit::assertion_traits专用化,或者只是避免CPPUNIT_ASSERT_EQUAL并使用CPPUNIT_ASSERT

CPPUNIT_ASSERT(lst.begin() == lst.end());