I am writing unit tests to exercise various code paths involving a factory class.
The factory returns a std::unique_ptr to a base type:
class Base {};
class Derived1 : public class Base {};
class Derived2 : public class Base {};
std::unique_ptr<Base> Type::Factory(enum rtype) const {
switch(rtype) {
case d1: return std::make_unique<Derived1>();
case d2: return std::make_unique<Derived2>();
default: return std::make_unique<Derived1>();
}
}
So in the test I want to ensure that the correct type is returned (factories are breeding ground for cut'n'paste bugs).
Is there a way of checking what type is returned?
This: EXPECT_TRUE(typeid(Derived1), typeid(type.get()); is false because the type.get() is that of Base and not the rtype that was passed in.
typeid( type.get() )will get thetypeidof the base pointer, i.e. the type thatget()is declared as returning. To get the real dynamic type of the pointed-to object, whatever that may be, you should dereference the pointer: