C++, google test/mock: assertion to test and object type
Asked Answered
O

2

5

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.

Oculus answered 6/8, 2011 at 16:34 Comment(1)
What exactly are you trying to check? What exactly have you tried?Plauen
C
4

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?

Coating answered 12/8, 2011 at 21:2 Comment(1)
Thanks, but yes, I'm already doing that, I'm just asking if it's a gtest alternative. (Like A<> matcher in gmock).Oculus
C
3

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.

Corallite answered 20/8, 2013 at 10:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.