[英]How to implement a custom matcher to check for object equality in Catch2
I'm new to unit testing in C++ with Catch2 .我是 C++ 单元测试的新手 Catch2 。 Lastly, I was trying to implement a custom Matcher to test if the fields of a given object match the ones I provide.
最后,我试图实现一个自定义匹配器来测试给定对象的字段是否与我提供的字段匹配。 The object in question good be like:
有问题的对象好象:
class Book {
private:
int chapters;
int pages;
public:
int GetChapters();
int GetPages();
};
My matcher would be used like this in a test case:我的匹配器将在测试用例中像这样使用:
TEST_CASE("Books info is correct")
{
Book myBook;
CHECK_THAT(myBook, IsCorrect(5, 150));
CHECK_THAT(myBook, IsCorrect(10, 325));
}
Following the example in the documentation, my intent has been:按照文档中的示例,我的意图是:
// The matcher class
class BookCheck : public Catch::MatcherBase<Book> {
Book book;
int chapters = -1;
int pages = -1;
public:
BookCheck(int chapters, int pages) : chapters(chapters), pages(pages) {}
// Performs the test for this matcher
bool match( Book& b ) const override {
return b.GetChapters() == chapters && b.GetPages() == pages;
}
virtual std::string describe() const override {
ostringstream ss;
//ss << "is between " << m_begin << " and " << m_end; // TODO
return ss.str();
}
};
// The builder function
inline BookCheck IsCorrect(int chapters, int pages) {
return BookCheck(chapters, pages);
}
When I compile this code, I get this errors:当我编译此代码时,出现以下错误:
error: 'bool BookCheck::match(Book&) const' marked 'override', but does not override错误:“bool BookCheck::match(Book&) const”标记为“覆盖”,但不覆盖
error: invalid abstract return type 'BookCheck'错误:无效的抽象返回类型“BookCheck”
error: invalid abstract return type for function 'BookCheck IsCorrect(int, int)'错误:函数“BookCheck IsCorrect(int, int)”的抽象返回类型无效
error: invalid cast to abstract class type 'BookCheck'错误:无效转换为抽象类类型“BookCheck”
Could you point me what am I doing wrong here?你能指出我在这里做错了什么吗?
Your match
method override is ill-formed.您的
match
方法覆盖格式错误。 Catch::MatcherBase::match
takes object as reference-to-const, so object will not be modified in method body. Catch::MatcherBase::match
将对象作为const 的引用,因此不会在方法体中修改对象。 Signature for Catch::MatcherBase::match
is: Catch::MatcherBase::match
签名是:
virtual bool match(ObjectT const& arg) const
So Your match
override implementation should be:所以你的
match
覆盖实现应该是:
bool match(Book const& b) const override {
return b.GetChapters() == chapters && b.GetPages() == pages;
}
Additionally You need to mark Your Book
getters const
in order to keep const correctness :此外,您需要将 Your
Book
getters 标记为const
以保持const 的正确性:
int GetChapters() const;
int GetPages() const;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.