How to check std::type_info with Google Test?

84 Views Asked by At

Having std::any in some classes, I'm looking for a good approach for a unit test checking if the contained value has the correct type. Because there are a lot of such test cases, I'm willing to introduce a custom matcher or macro.

Here are some approaches I tried:

std::any x = 73;
EXPECT_THAT(x.type(), Eq(typeid(double)));

does not compile, saying error: ‘std::type_info::type_info(const std::type_info&)’ is private within this context (is not copyable).

std::any x = 73;
EXPECT_EQ(x.type(), typeid(double));

works, but results in following message, which is not very readable:

Expected equality of these values:
  x.type()
    Which is: 16-byte object <D8-11 5F-DB 75-7F 00-00 54-F5 57-DB 75-7F 00-00>
  typeid(double)
    Which is: 16-byte object <D8-11 5F-DB 75-7F 00-00 93-F5 57-DB 75-7F 00-00>
std::any x = 73;
EXPECT_THAT(x.type().name(), Eq(typeid(double).name()));

gives a much better error message (see below), but I'd prefer comparing types, not type names.

Value of: x.type().name()
Expected: is equal to 0x7f2a6317f593 pointing to "d"
  Actual: 0x7f2a6317f554 pointing to "i" (of type char const*)

Could a custom matcher help here? Ideally I'd like to have something like

EXPECT_THAT(x.type(), IsOfType(typeid(double)));

or

EXPECT_TYPE_EQ(x.type(), typeid(double));

checking the type and giving a more or less readable error message in case it fails.

Or do you think this is overpedantic and simply comparing type names is a more pragmatic approach?

0

There are 0 best solutions below