c++ - 为什么谷歌测试 ASSERT_FALSE 在方法中不起作用,但 EXPECT_FALSE 可以

标签 c++ googletest

ASSERT_TRUEASSERT_FALSE 都没有在 LibraryTest 类中编译并出现错误。

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> &'

它在我使用的任何 TEST_F 中都有效。 但是 EXPECT_FALSELibraryTest 类和 TEST_F 方法中编译得很好。

如何在 TEST_F 使用的方法中使用 ASSERT

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);
}

最佳答案

如果新的 C++ 标准是您项目的一部分,那么您可以简单地解决它。

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

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

或者甚至重新定义那些宏:

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_); }()

...

关于c++ - 为什么谷歌测试 ASSERT_FALSE 在方法中不起作用,但 EXPECT_FALSE 可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17961900/

相关文章:

c++ - 如何使用自定义非纯交换函数参数化算法?

c++ - 在 Windows dll 中使用 boost::asio::deadline_timer 时出现死锁

c++ - 为什么在调试过程中有时窗口标题黑色和按钮无框

c++ - 如何处理用于构建 google test exec 文件的自动工具?

c++ - gmock SetArgReferee : Set a non-copyable non-moveable object

c++ - 如果预期调用过度饱和,谷歌测试/模拟测试失败

c++ - 如何从另一个 lambda 函数调用 lambda 函数

c++ - 如何保护数组定义免受非零值初始化不完整的影响?

c++ - 在googletest中访问 protected 变量

c++ - CMake:尝试在 Jenkins Build Machine 上运行时出现 "Linked Library"错误(0xc0000135)