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

When I use the ASSERT_TRUE() provided in Gtest , I get below the error. return type does not match function type with underscore 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 } 
+7
source share
3 answers

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

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

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

Due to C ++ features, to support syntax for streaming messages to ASSERT_ *, for example.

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

we had to abandon the use of ASSERT * and FAIL * (but not EXPECT * and ADD_FAILURE *) in constructors and destructors. The workaround is to move the contents of your constructor / destructor to the void private element function or switch to EXPECT _ * () if that works. This section of the user guide explains this.

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

+1
source

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

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

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

Possible fixes include not using hard stops:

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

or change the type of returned methods, if not required:

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

or return via the link:

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

The fun method has a return type of bool , so it still needs to return something.

ASSERT_TRUE is a macro that checks that something is true, it will not cause a return for you. In fact, you can have a lot of ASSERT_TRUE per line and (assuming all of them are true), they will all be executed one after another. Think of the ASSERT_TRUE macro as a function call, even if it's not technically.

This should work:

 bool abc::fun() { ASSERT_TRUE(fun1()); return true; } 
+1
source

All Articles