TEST_CASE("Functions of Square")
{
std::array<Point, 4> a_Vertices{Point(2, 2), Point(2, 4), Point(4, 2), Point(4, 4)};
Square a_Square(a_Vertices, true);
SECTION("Square is initialized properly")
{
REQUIRE(a_Square.get_Vertex_0() == Point(2, 1));
}
}
使用catch2单元测试框架,我想覆盖catch2描述方法,这样它就会打印出我的类型,而不是{?}=={?}
我也尝试过通过匹配器方法
class Point_Matcher : public Catch::MatcherBase<Point>
{
private:
Point p_;
public:
Point_Matcher(const Point &a_Point)
: p_(a_Point) {}
bool match(Point const &a_Point) const override
{
return a_Point == p_;
}
virtual std::string describe() const override
{
std::ostringstream oss;
oss << "not the same as Point (" << p_.get_X() << ", " << p_.get_Y() << ")";
return oss.str();
}
};
inline Point_Matcher is_Same(const Point &a_Point)
{
return Point_Matcher(a_Point);
}
TEST_CASE("Functions of Square")
{
std::array<Point, 4> a_Vertices{Point(2, 2), Point(2, 4), Point(4, 2), Point(4, 4)};
Square a_Square(a_Vertices, true);
SECTION("Square is initialized properly")
{
REQUIRE_THAT(a_Square.get_Vertex_0(), is_Same(Point(2, 1)));
}
}
但是,它只显示指定为测试的对象,而不会显示正在测试的对象。输出将{?}与点(2,1(不同
在https://github.com/catchorg/Catch2/blob/master/docs/tostring.md#top建议的方法是覆盖运算符<lt;std::ostream,然而,我不知道我应该怎么做后,我超载了运营商。
提前感谢您的回答
编辑:操作员的过载<lt;点对象的如下
std::ostream &operator<<(std::ostream &os, const Point &p)
{
os << "Point (" << p.get_X() << ", " << p.get_Y();
return os;
}
换句话说,我的目标是在这种情况下点(x,y(与点(x、y(不同
通常使用两种方法。您提到的文档中对两者都进行了描述。
- 运算符<lt;std::ostream的过载,限制为:
您应该将此函数放在与类型相同的命名空间中,或者全局命名空间,并在包含Catch的头球
因此,您的运算符重载是可以的,只需将其放在#include "catch.hpp"
之前即可。
#define CATCH_CONFIG_MAIN
#include <array>
#include "Point.h"
#include "Square.h"
std::ostream &operator<<(std::ostream &os, Point const& p)
{
os << "Point (" << p.get_X() << ", " << p.get_Y() << ")";
return os;
}
#include "catch.hpp"
TEST_CASE("Functions of Square")
{
std::array<Point, 4> a_Vertices{Point(2, 2), Point(2, 4), Point(4, 2), Point(4, 4)};
Square a_Square(a_Vertices, true);
SECTION("Square is initialized properly")
{
REQUIRE_THAT(a_Square.get_Vertex_0(), is_Same(Point(2, 1)));
}
}
2.Catch::StringMaker专业化,使用额外的字符串流来正确格式化输出。
#define CATCH_CONFIG_MAIN
#include <array>
#include <sstream>
#include "Point.h"
#include "Square.h"
#include "catch.hpp"
namespace Catch
{
template <> struct StringMaker<Point>
{
static std::string convert(Point const& p)
{
std::stringstream buf;
buf << "Point (" << p.get_X() << ", " << p.get_Y() << ")";
return << buf.str();
}
};
}
TEST_CASE("Functions of Square")
{
std::array<Point, 4> a_Vertices{Point(2, 2), Point(2, 4), Point(4, 2), Point(4, 4)};
Square a_Square(a_Vertices, true);
SECTION("Square is initialized properly")
{
REQUIRE_THAT(a_Square.get_Vertex_0(), is_Same(Point(2, 1)));
}
}
这种方法避免了全局名称空间污染,并允许您屏蔽任何其他先前定义的<<
运算符。首先将使用StringMaker
专业化。