6
votes

Both the ASSERT_TRUE and ASSERT_FALSE does not compile in the LibraryTest class with the error.

error C2664: 'std::basic_string<_Elem,_Traits,_Alloc>::basic_string(const std::basic_string<_Elem,_Traits,_Alloc> &)' : cannot convert parameter 1 from 'void' to 'const std::basic_string<_Elem,_Traits,_Alloc> &'

It works since in any TEST_F I use. But the EXPECT_FALSE compiles fine in both the LibraryTest class and the TEST_F methods.

How can I use ASSERT in the method used by a TEST_F?

class LibraryTest : public ::testing::Test
{
public:
    string create_library(string libName)
    {
        string libPath = setup_library_file(libName);

        LibraryBrowser::reload_models();

        ASSERT_FALSE(library_exists_at_path(libPath));
        new_library(libName, libPath);
        ASSERT_TRUE(library_exists_at_path(libPath));
        EXPECT_FALSE(library_exists_at_path(libPath));
        return libPath;
    }
};

TEST_F(LibraryTest, libraries_changed)
{
    string libName = "1xEVTestLibrary";
    string libPath = create_library(libName);
}
2

2 Answers

3
votes

Functions using any of the gtest assertions need to return void. In your case, you could change your function thus:

void create_library(const string &libName, string &libPath) {
  libPath = ...
  ASSERT_FALSE(...)
}

And use it like this:

TEST_F(LibraryTest, libraries_changed) {
  string libName = "foo";
  string libPath;
  create_library(libName, libPath);
}
5
votes

If new C++ standard is a part of your project, then you can simply workaround that.

#if __cplusplus < 201103L
#error lambda is not supported
#endif

void create_library(const string &libName, string &libPath) {
  libPath = ...
  []() -> void { ASSERT_FALSE(...); }();
}

Or even redefine those macros:

mygtest.hpp

#include <gtest/gtest.hpp>

#if __cplusplus < 201103L
#error lambda is not supported
#endif

// gtest asserts rebind with the `void` error workaround (C++11 and higher is required)
#undef ASSERT_TRUE
#define ASSERT_TRUE(condition) []() -> void { GTEST_TEST_BOOLEAN_((condition), #condition, false, true, GTEST_FATAL_FAILURE_); }()
#undef ASSERT_FALSE
#define ASSERT_FALSE(condition) []() -> void { GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, GTEST_FATAL_FAILURE_); }()

...