【问题标题】:How to pass STL containers as arguments to BOOST_CHECK_EQUAL?如何将 STL 容器作为参数传递给 BOOST_CHECK_EQUAL?
【发布时间】:2011-06-17 17:00:33
【问题描述】:

例如,假设我们要测试这个类:

struct TestMe {
  vector<int> getSomething();
}

而测试函数由:

...
vector<int> Expected;
TestMe TM;
...
Result = TM.getSomething();
BOOST_CHECK_EQUAL(Result, Expected);
...

STL 向量提供了一个免费的运算符==,但它没有提供一个运算符

【问题讨论】:

  • 没有operator&lt; &lt;这样的东西,你是说operator&lt;还是operator&lt;&lt;?
  • 我想get 应该是getSomething。 operator&lt;&lt; 和什么有什么关系? BOOST_CHECK_EQUAL 使用 == 运算符。
  • @Potato:是的,但是如果检查失败,它会尝试使用operator&lt;&lt; 打印出这两个值。因此BOOST_CHECK_EQUAL 需要operator== 和operator&lt;&lt;。

标签: c++ unit-testing boost stl


【解决方案1】:

我认为你应该使用BOOST_CHECK_EQUAL_COLLECTIONS,它会测试每个元素并打印出不匹配的位置:

BOOST_CHECK_EQUAL_COLLECTIONS(Result.begin(), Result.end(), Expected.begin(), Expected.end());

【讨论】:

    【解决方案2】:

    我认为Philipp's answer 是最好的答案。但是,如果需要,您可以制作自己的模板 operator&lt;&lt;(),它适用于矢量和其他标准容器:

    // Will write out any container that has begin(), end() and a const_iterator type
    template <typename C>
    std::ostream& output_container(std::ostream& os, C const& c) {
        for (typename C::const_iterator i = c.begin(); i != c.end(); ++i) {
            if (i != c.begin()) os << ", ";
            os << *i;
        }
    
        return os;
    }
    
    // Overload operators for each container type that forward to output_container()
    template <typename T>
    std::ostream& operator<<(std::ostream& os, vector<T> const& c) {
        return output_container(os, c);
    }
    
    template <typename T>
    std::ostream& operator<<(std::ostream& os, list<T> const& c) {
        return output_container(os, c);
    }
    

    虽然您可以简单地将 output_container() 重命名为 operator&lt;&lt;() 并摆脱每个容器类型的 operator&lt;&lt;() 模板,从而捕获所有在类类型上使用 &lt;&lt; 的尝试,这可能会干扰其他类型的 operator&lt;&lt;() 函数模板。

    【讨论】:

    • 我在发布我的问题之前尝试了一个非常相似的解决方案,但它没有编译。我复制粘贴了您的解决方案并得到了相同的错误:错误 C2679: binary '' 类型的右手操作数(或者没有可接受的转换) 1> 与 1> [ 1> _Ty=uint8_t 1> ]
    • @zr:听起来名字查找失败了。您确定所有这些模板在使用之前都已定义吗?
    • @zr:看起来你实际上使用的是vector&lt;uint8_t&gt;,而不是宣传的vector&lt;int&gt;——是这样吗?否则我很困惑。
    • @JRH:这两个问题的答案都是肯定的。在示例中,为了简单起见,我使用了 int。
    • @zr:我怀疑问题在于BOOST_CHECK_EQUAL() 扩展为对调用operator&lt;&lt;() 的模板函数(我们称之为f())的调用,并且在这一点上f() 已定义,我们的 operator&lt;&lt;() 模板未定义。如果是这种情况,那么您需要提出一个前向声明 (template &lt;typename T&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, std::vector&lt;T&gt; const&amp;);)before #包括定义 BOOST_CHECK_EQUAL() 的 Boost 标头。 (我知道,糟糕。)
    【解决方案3】:

    我一直在寻找类似的东西,一种自定义输出字符串以打印十六进制整数的方法。将运算符注入 std 命名空间会起作用,但我测试中的每个 BOOST_CHECK 都会以十六进制打印。

    所以我在 boost 命名空间中注入了一些自定义运算符,我可以使用一些全局布尔值来控制它们。

    在这里查看我的答案boost-check-fails-to-compile-operator-for-custom-types。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-28
      • 2017-04-26
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      相关资源
      最近更新 更多