I have this (not really, is just a simple example):
template<class T>
T foo() {...}
I need to check the result type of the function (here not make any sense, my example is more complex I promise), does google test/mock support this kind of assertion?
I try EXPECT_THAT with A< T >, but I cannot make that work.
Thanks.
Google Test is for run-time tests. The type of a function is determined at compile time, before Google Test ever enters the picture.
You could use result_of
and assert that the typeid value is the same, something like this:
EXPECT_EQ(typeid(int), typeid(std::result_of<foo<int>() >::type));
Another option is to forego an explicit test of the return type and just use the function as it's expected to be used. If there's something wrong with the return type, the compiler will tell you before you ever try running the test. That's probably better than requiring one specific return type, anyway; for example, if the return type turns out to be long
instead of the expected int
, but all your other tests still pass, then was int
really so important in the first place?
You can use ::testing::StaticAssertTypeEq(); with std::result_of. You can also use typed tests. Complete example:
#include <type_traits>
template<class T>
T foo(int) {...}
///Boilerplate code for using several types
template <typename T>
class ResultTest : public testing::Test {}
typedef ::testing::Types<float, double, int, char*, float**> MyTypes; //Types tested!
TYPED_TEST_CASE(ResultTest , MyTypes);
///Real test
TYPED_TEST(ResultTest , ResultTypeComprobation) {
//It will be checked at compile-time.
::testing::StaticAssertTypeEq<TypeParam, std::result_of(foo<TypeParam>)>();
}
However, test will be instanced and run at run-time without doing anything. Weird, but I couldn't find anything better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With