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描述方法,以便它可以打印出我的类型,而不是{?} == {?}
我也尝试过通过matcher方法
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中,建议的方法是重写std::ostream的operator<<,但是,在重载操作符之后,我不知道该做什么。
提前谢谢你的回答
编辑: Point的operator<<重载如下
std::ostream &operator<<(std::ostream &os, const Point &p)
{
os << "Point (" << p.get_X() << ", " << p.get_Y();
return os;
}
换句话说,我瞄准的输出在本例中是点(x,y),而不是点(x,y)
发布于 2020-02-24 18:48:27
有两种方法是常用的。这两者都是在您提到的文档中描述的。
应该将此函数放在与类型或全局命名空间相同的名称空间中,并在包含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)));
}
}
#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
专门化。
https://stackoverflow.com/questions/60372706
复制相似问题