无法引用测试夹具的默认构造函数
Default constructor of test fixture cannot be referenced
我在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);
};
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 初始化具有非默认构造函数的std::数组项的更好方法
- 具有默认模板类型的默认构造函数的类型推导
- 如何使用非默认构造函数实例化模板化类
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 声明没有默认构造函数的字段
- 没有默认构造函数作为模板参数的自定义比较器
- C++17 没有默认构造函数的地图放置(私有默认构造函数)
- 使用移动调用对等构造函数unique_ptr默认构造函数
- C++复制构造函数和默认构造函数
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- 为什么即使我调用参数化构造函数也会调用默认构造函数?
- 具有非默认构造函数的单例类
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 如何处理没有默认构造函数但在另一个构造函数中构造的对象?
- 在C++中使用默认构造函数初始化对象的不同方法
- 在没有默认构造函数的情况下创建的派生对象
- 强制使用默认构造函数对成员进行未初始化的声明
- 使用默认构造函数初始化对象的不同方法
- 创建类类型的动态分配数组,其中类不得具有默认构造函数