![](/img/trans.png)
[英]How do you mock and test the same function in C/C++ with FFF and Google Test?
[英]C++, google test/mock: assertion to test and object type
我有这个(不是真的,只是一个简单的例子):
template<class T>
T foo() {...}
我需要检查函数的结果类型(这里没有任何意义,我的例子更复杂,我保证),google test / mock是否支持这种断言?
我用A <T>尝试EXPECT_THAT,但我无法做到这一点。
谢谢。
Google Test适用于运行时测试。 在Google Test进入图片之前,在编译时确定函数的类型。
你可以使用result_of
并断言typeid值是相同的,如下所示:
EXPECT_EQ(typeid(int), typeid(std::result_of<foo<int>() >::type));
另一种选择是放弃对返回类型的显式测试,并且只使用预期使用的函数。 如果返回类型有问题,编译器会在您尝试运行测试之前告诉您。 无论如何,这可能比要求一种特定的返回类型更好; 例如,如果返回类型变为long
而不是期望的int
,但是所有其他测试仍然通过,那么int
真的如此重要吗?
你可以使用:: testing :: StaticAssertTypeEq(); 使用std :: result_of 。 您也可以使用类型化测试 。 完整的例子:
#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>)>();
}
但是,测试将实例化并在运行时运行而不做任何事情。 很奇怪,但我找不到更好的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.