简体   繁体   English

为什么谷歌测试ASSERT_FALSE在方法中不起作用,但EXPECT_FALSE起作用

[英]Why does google test ASSERT_FALSE not work in methods but EXPECT_FALSE does

Both the ASSERT_TRUE and ASSERT_FALSE does not compile in the LibraryTest class with the error. 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> &' 错误C2664:'std :: basic_string <_Elem,_Traits,_Alloc> :: basic_string(const std :: basic_string <_Elem,_Traits,_Alloc>&)':无法将参数1从'void'转换为'const std :: basic_string <_Elem,_Traits,_Alloc>&'

It works since in any TEST_F I use. 它起作用,因为在我使用的任何TEST_F But the EXPECT_FALSE compiles fine in both the LibraryTest class and the TEST_F methods. 但是EXPECT_FALSELibraryTest类和TEST_F方法中编译都很好。

How can I use ASSERT in the method used by a 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);
}

If new C++ standard is a part of your project, then you can simply workaround that. 如果新的C ++标准是项目的一部分,那么您可以简单地解决这个问题。

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

...

Functions using any of the gtest assertions need to return void . 使用任何gtest断言的函数需要返回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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM