在使用 gcc 6.2.0 的 Catch Unit Test v1.8.1 中,当测试失败时,我试图通过将向量传递给INFO(...)
or来方便地输出向量的内容CAPTURE(...)
。为此,我重载了流插入运算符:
#include <Catch/single_include/catch.hpp>
#include <vector>
#include <iostream>
#define THIS_WORKS_BUT_EXTENDING_NAMESPACE_STD_IS_ILLEGAL
#ifdef THIS_WORKS_BUT_EXTENDING_NAMESPACE_STD_IS_ILLEGAL
namespace std {
#endif
std::ostream& operator<<( std::ostream& os, const std::vector<int>& v ) {
for ( const auto& e : v ) {
os << e << " ";
}
return os;
}
#ifdef THIS_WORKS_BUT_EXTENDING_NAMESPACE_STD_IS_ILLEGAL
} //namespace std
#endif
int some_operation_on_vector( const std::vector<int>& v ) {
return 1;
}
SCENARIO( "some scenario" )
{
GIVEN( "a vector" )
{
const auto the_vector = std::vector<int>{ 1, 2, 3, 4, 5 };
WHEN( "some result is calculated from the vector" )
{
const auto actual_result = some_operation_on_vector( the_vector );
THEN( "the result should be correct. If not, print out the vector." )
{
const auto expected_result = 0;
CAPTURE( the_vector ); // <--------
//^^^^
//How do I legally make this work?
REQUIRE( expected_result == actual_result );
}
}
}
}
std
如果我(非法)如上所述扩展命名空间,那么它可以工作,我会看到所需的输出:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
catchtestexample is a Catch v1.8.1 host application.
Run with -? for options
-------------------------------------------------------------------------------
Scenario: some scenario
Given: a vector
When: some result is calculated from the vector
Then: the result should be correct. If not, print out the vector.
-------------------------------------------------------------------------------
ExampleTest.cpp:91
...............................................................................
ExampleTest.cpp:95: FAILED:
REQUIRE( expected_result == actual_result )
with expansion:
0 == 1
with message:
the_vector := 1 2 3 4 5
===============================================================================
test cases: 1 | 1 failed
assertions: 1 | 1 failed
但是为了合法,当我尝试将operator<<
重载移出std
命名空间并进入全局命名空间(通过注释 out )时,由于将向量传递给宏#define THIS_WORKS_BUT_EXTENDING_NAMESPACE_STD_IS_ILLEGAL
,代码无法编译。CAPTURE()
根据Catch docs,我尝试用operator <<
重载替换Catch::toString
重载:
#include <string>
#include <sstream>
namespace Catch {
std::string toString( const std::vector<int>& v ) {
std::ostringstream ss;
for ( const auto& e : v ) {
ss << e << " ";
}
return ss.str();
}
}
或Catch::StringMaker
专业:
#include <string>
#include <sstream>
namespace Catch {
template<> struct StringMaker<std::vector<int>> {
static std::string convert( const std::vector<int>& v ) {
std::ostringstream ss;
for ( const auto& e : v ) {
ss << e << " ";
}
return ss.str();
}
};
}
CAPTURE()
但在任何一种情况下,由于将向量传递给宏,测试仍然无法编译。
Catch 文档说将operator<<
重载放入与您的类型相同的命名空间,但std::vector
不是我的类型,并且将该重载放入命名空间std
是非法的。
但是我能够找到CAPTURE()
(或INFO()
,或WARN()
等)接受std::vector
参数的唯一方法是非法将operator<<
重载放入命名空间std
。
有没有适当的、合法的方式来做到这一点?