c++ - ASSERT_TRUE() 返回类型与 gtest 中的函数类型不匹配

标签 c++ visual-studio-2010 googletest

当我使用 Gtest 中提供的 ASSERT_TRUE() 时,出现以下错误。 返回类型与函数类型不匹配,在 VS 2010. 中带有下划线。

abc.h

#include "gtest\gtest.h"

class abc {
pubilc:
    bool fun();
    private:
    bool fun1();
};

abc.c

bool abc::fun()
{
    ASSERT_TRUE(fun1()); // Getting error: return type does not match function type
}

bool abc::fun1()
{
    return true; // True or false depanding on operation
}

最佳答案

ASSERT_TRUE 是一个宏。展开后它将包含一个分支,如:

if (fun1() == false) {
   return;
}

这就是 ASSERT_TRUE 在失败时硬停止的方式,但这也意味着您的方法 bool abc::fun() 现在有一个 void 返回退出路径,与其签名冲突。

可能的修复包括不使用硬停止断言:

bool abc::fun(){
    bool result = fun1();
    EXPECT_TRUE(result); //No return in expansion
                         //No hard stop!
    return result;
}

或在不需要时更改您的方法返回类型:

void abc::fun(){
    ASSERT_TRUE(fun1()); //Hard stop on failure
}

或通过引用返回:

void abc::fun(bool &outResult){
   outResult = fun1();  //return result by reference
   ASSERT_TRUE(result);
}

关于c++ - ASSERT_TRUE() 返回类型与 gtest 中的函数类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12617806/

相关文章:

C++ : initialize input programmatically

用于提取 .zip 文件的 C++ 包装器代码?

c++ - excel xll :name of the calling function from within function

c++ - 谷歌测试夹具 : passing a class member size

c++ - CMake + GoogleTest 在小型库集合中给出重新定义错误

C++ 警告 : deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]

c++ - 将函数中创建的对象分配给成员变量

visual-studio-2010 - Visual Studio 2013给出 "Cannot add duplicate collection entry of type ‘mimeMap’“

javascript - JSON 的智能感知?

c++ - 在循环中添加预期的调用