假设我有以下抽象基类:
class Base {
public:
virtual void method() = 0;
virtual const bool operator==(const Base& other) const = 0;
};
一个具体的派生类。
class Derived : public Base {
public:
int value_;
Derived(int value) : value_(value) { }
virtual void method() { }
virtual const bool operator==(const Base& other) const {
const Derived& derived = dynamic_cast<const Derived&>(other);
return operator==(derived);
}
virtual const bool operator==(const Derived& other) const {
return value_ == other.value_;
}
};
使用Google Mock,我现在想断言在基类上定义的向量包含一个具体类的示例
TEST(ArrayContents, CompareAgainstDerivedClassElements) {
Derived d1(0);
Derived d2(0);
std::vector<Base*> v { &d1 };
ASSERT_THAT(v, Contains( Pointee(d2) ));
}
C ++抱怨它无法创建Eq
匹配器,因为Base
是一个抽象类。
error: no matching function for call to 'Eq'
note: candidate template ignored: substitution failure [with T = perseus::Base]: parameter type 'perseus::Base' is an abstract class
当我更改Base
时,它不再是抽象的:
class Base {
public:
virtual void method() { }
virtual const bool operator==(const Base& other) const { return false; }
};
C ++在std::bad_cast
表达式上抛出dynamic_cast
个异常。
Google Mock是否可以提出这样的断言?
答案 0 :(得分:0)
事实证明,解决方案是使用WhenDynamicCastTo
匹配器:
ASSERT_THAT(v, Contains( WhenDynamicCastTo<Derived*>(Pointee(d2)) ));
这样,我也不需要虚拟operator==
方法。