Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASSERT_TRUE() return type does not match function type in gtest

When I am using ASSERT_TRUE() provided in Gtest I am getting below error. return type does not match function type with an underline in 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
}
like image 891
Rasmi Ranjan Nayak Avatar asked Sep 27 '12 09:09

Rasmi Ranjan Nayak


2 Answers

ASSERT_TRUE is a macro. When expanded it will contain a branch like:

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

This is how ASSERT_TRUE does a hard stop on failure, but it also means that your method bool abc::fun() now has a void return exit path, in conflict with its signature.

Possible fixes include don't use hard stop asserts:

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

or change your methods return type if not needed:

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

or return by reference:

void abc::fun(bool &outResult){
   outResult = fun1();  //return result by reference
   ASSERT_TRUE(result);
}
like image 124
Downward Facing God Avatar answered Nov 10 '22 00:11

Downward Facing God


There is no return statement specified in fun() but it returns a bool. Add a return false; or return true; to fun() or change its return type to void:

void abc::fun()
{
    ASSERT_TRUE(fun1());
}

Based on My compiler complains that a constructor (or destructor) cannot return a value. What's going on? which states (verbatim):

Due to a peculiarity of C++, in order to support the syntax for streaming messages to an ASSERT_*, e.g.

ASSERT_EQ(1, Foo()) << "blah blah" << foo;

we had to give up using ASSERT* and FAIL* (but not EXPECT* and ADD_FAILURE*) in constructors and destructors. The workaround is to move the content of your constructor/destructor to a private void member function, or switch to EXPECT_*() if that works. This section in the user's guide explains it.

the return type must be void in functions that use ASSERT_*() macros.

like image 24
hmjd Avatar answered Nov 10 '22 00:11

hmjd