gmock 和 forward 声明的类

gmock and forward declared classes

本文关键字:声明 forward gmock      更新时间:2023-10-16

假设我有这个类并且类型管理器在 Base.h 中向前声明。

#include <Base.h>
class MockBase : public Base
{
public:
    MOCK_CONST_METHOD0( manager, const Manager&( ) );
    ...
};

我不打算在我的测试中使用此方法,所以我不想将经理类的定义包含在带有测试的文件中。

但我认为在编译 gmock 尝试准备错误消息并深入其肠道时,它需要管理器变量的地址,我有一个错误:

错误 C2027:使用未定义的类型"管理器" \external\googlemock\gtest\include\gtest\gtest-printers.h 146 1

我可以以某种方式避免包含我不会使用的方法的前向声明类型的定义的文件吗?

这个想法是为 UT 定义一个泛型 ostream 运算符,该运算符仅对前向声明的类型激活。它必须位于全局命名空间中。如果包括,它可以解决所有类型的前向申报gmock问题。
用户仍然可以提供自定义PrintTo函数,即使对于前向声明的引用也是如此,因为PrintTo似乎是首先调用的。它适用于 gmock 1.7,在 GCC 中具有C++14

// A class to determine if definition of a type is available or is it forward declared only
template <class, class = void>
struct IsDefined : std::false_type
{};
template <class T>
struct IsDefined<T, std::enable_if_t<std::is_object<T>::value 
                                     && not std::is_pointer<T>::value 
                                     && (sizeof(T) > 0)>>
    : std::true_type
{};
// It has to be in global namespace
template <
    typename T,
    typename = std::enable_if_t<
        not IsDefined<T>::value and 
        not std::is_pointer<T>::value and 
        std::is_object<T>::value>>
std::ostream& operator<<(std::ostream& os, const T& ref)
{
    os << "Forward declared ref: " << static_cast<const void*>(&ref);
    // assert(false); // Could assert here as we do not want it to be executed
    return os;
}

我已经通过定义一个 PrintTo 函数来解决这个问题,因此 gtest 不会尝试使用导致问题的 TypeWithoutFormatter 函数。这很不幸,我不确定正确的修复方法是什么。

namespace Foo { void PrintTo(const Bar& x, ::std::ostream* os) { *os << "Bar " << &x; }}