无法引用测试夹具的默认构造函数

Default constructor of test fixture cannot be referenced

本文关键字:默认 构造函数 夹具 测试 引用      更新时间:2023-10-16

我在Visual Studio 2015中使用Google test编译带有测试夹具的文件时遇到问题。我试图为其创建测试夹具的类名为Counter

测试中的计数器类有一个受保护的默认构造函数,用于初始化各种受保护的成员变量。Counter类中的这些成员变量包括对象、指向常量对象的指针、int和double。

DefaultConstructor测试编译失败,并显示以下错误消息the default constructor of "CounterTest" cannot be referenced -- it is a deleted function

需要明确的是,我正在尝试在CounterTest类(测试夹具)中实例化一个Counter对象(使用它的默认构造函数),以便在各个测试中使用。

// Counter.h
class Counter : public ConfigurationItem {
protected:
    EventId startEventIdIn_;
    int numStarts_;
    CounterConfigurationItem_Step const* currentStep_;
    double startEncoderPosMm_;
private: 
    FRIEND_TEST(CounterTest, DefaultConstructor);
};
// GTest_Counter.cpp
class CounterTest : public ::testing::Test {
protected:
    Counter counter;
};
TEST_F(CounterTest, DefaultConstructor)
{
    ASSERT_EQ(0, counter.numStarts_);
}

我做错了什么?是否有可能让测试夹具与正在测试受保护/私有成员访问的类成为朋友?谢谢

我猜您没有发布类CounterTest的完整定义,因为如果我添加一个伪Counter类,您发布的代码编译时不会出错:

class Counter
{
public:
    int numStarts_;
};

由于错误消息表明CounterTest类没有默认构造函数,我猜您向该类添加了一个非默认构造函数。在C++中,这意味着如果不显式指定默认构造函数,则默认构造函数将被删除。这是一个问题,因为googletest只使用默认构造函数实例化测试夹具类,而不能使用非默认构造函数来实例化测试夹具。如果您需要在每次测试前执行一些不同的操作,您可以将带有参数的SetUp方法版本添加到fixture类中,并在每次测试开始时使用所需的输入参数调用它。

解决方案:将CounterTest声明为友元类。

class Counter : public ConfigurationItem {
protected:
    EventId startEventIdIn_;
    int numStarts_;
    CounterConfigurationItem_Step const* currentStep_;
    double startEncoderPosMm_;
private: 
    friend class CounterTest;
    FRIEND_TEST(CounterTest, DefaultConstructor);

};